com.alipay.sofa.rpc.common.RpcConfigs Java Examples

The following examples show how to use com.alipay.sofa.rpc.common.RpcConfigs. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractSofaRpcFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testNeedToLoadProvider() {
    SentinelSofaRpcProviderFilter providerFilter = new SentinelSofaRpcProviderFilter();
    ProviderConfig providerConfig = new ProviderConfig();
    providerConfig.setInterfaceId(Serializer.class.getName());
    providerConfig.setId("AAA");
    FilterInvoker invoker = new FilterInvoker(null, null, providerConfig);
    assertTrue(providerFilter.needToLoad(invoker));

    providerConfig.setParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "false");
    assertFalse(providerFilter.needToLoad(invoker));

    providerConfig.setParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "");
    assertTrue(providerFilter.needToLoad(invoker));

    RpcConfigs.putValue(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "false");
    assertFalse(providerFilter.needToLoad(invoker));
}
 
Example #2
Source File: AbstractSofaRpcFilterTest.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
@Test
public void testNeedToLoadConsumer() {
    SentinelSofaRpcConsumerFilter consumerFilter = new SentinelSofaRpcConsumerFilter();
    ConsumerConfig consumerConfig = new ConsumerConfig();
    consumerConfig.setInterfaceId(Serializer.class.getName());
    consumerConfig.setId("BBB");
    FilterInvoker invoker = new FilterInvoker(null, null, consumerConfig);
    assertTrue(consumerFilter.needToLoad(invoker));

    consumerConfig.setParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "false");
    assertFalse(consumerFilter.needToLoad(invoker));

    consumerConfig.setParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "");
    assertTrue(consumerFilter.needToLoad(invoker));

    RpcConfigs.putValue(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "false");
    assertFalse(consumerFilter.needToLoad(invoker));
}
 
Example #3
Source File: RestTracerModule.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
/**
 * 是否启动Tracer
 *
 * @return 是否开启
 */
public static boolean isEnable() {
    boolean enable = "sofaTracer".equals(RpcConfigs.getStringValue(RpcOptions.DEFAULT_TRACER));
    if (enable) {
        try {
            ClassUtils.forName("javax.ws.rs.container.ContainerRequestFilter");
            ClassUtils.forName("javax.ws.rs.container.ContainerResponseFilter");
            ClassUtils.forName("org.jboss.resteasy.core.interception.PostMatchContainerRequestContext");
            ClassUtils.forName("org.jboss.resteasy.plugins.server.netty.NettyHttpRequest");
            ClassUtils.forName("org.jboss.resteasy.plugins.server.netty.NettyHttpResponse");
        } catch (Exception e) {
            return false;
        }
    }
    return enable;
}
 
Example #4
Source File: ProtocolFactory.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
private static ExtensionLoader<Protocol> buildLoader() {
    ExtensionLoader<Protocol> extensionLoader = ExtensionLoaderFactory.getExtensionLoader(Protocol.class);
    extensionLoader.addListener(new ExtensionLoaderListener<Protocol>() {
        @Override
        public void onLoad(ExtensionClass<Protocol> extensionClass) {
            // 除了保留 alias:Protocol外, 需要保留 code:Protocol
            Protocol protocol = extensionClass
                .getExtInstance();
            TYPE_PROTOCOL_MAP.put(extensionClass.getCode(), protocol);
            TYPE_CODE_MAP.put(extensionClass.getAlias(), extensionClass.getCode());
            if (RpcConfigs.getBooleanValue(RpcOptions.TRANSPORT_SERVER_PROTOCOL_ADAPTIVE)) {
                maxMagicOffset = 2;
                registerAdaptiveProtocol(protocol.protocolInfo());
            }
        }
    });
    return extensionLoader;
}
 
Example #5
Source File: TimeWindowRegulator.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Override
public void init() {
    String measureStrategyAlias = RpcConfigs
        .getOrDefaultValue(RpcOptions.AFT_MEASURE_STRATEGY, "serviceHorizontal");
    String regulationStrategyAlias = RpcConfigs.getOrDefaultValue(RpcOptions.AFT_REGULATION_STRATEGY,
        "serviceHorizontal");
    String degradeStrategyAlias = RpcConfigs.getOrDefaultValue(RpcOptions.AFT_DEGRADE_STRATEGY, "weight");
    String recoverStrategyAlias = RpcConfigs.getOrDefaultValue(RpcOptions.AFT_RECOVER_STRATEGY, "weight");

    measureStrategy = ExtensionLoaderFactory.getExtensionLoader(MeasureStrategy.class).getExtension(
        measureStrategyAlias);
    regulationStrategy = ExtensionLoaderFactory.getExtensionLoader(RegulationStrategy.class).getExtension(
        regulationStrategyAlias);
    degradeStrategy = ExtensionLoaderFactory.getExtensionLoader(DegradeStrategy.class).getExtension(
        degradeStrategyAlias);
    recoverStrategy = ExtensionLoaderFactory.getExtensionLoader(RecoverStrategy.class).getExtension(
        recoverStrategyAlias);

    InvocationStatFactory.addListener(listener);
}
 
Example #6
Source File: HystrixFilter.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
private boolean isHystrixEnabled(AbstractInterfaceConfig config) {
    String consumerHystrixEnabled = config.getParameter(HystrixConstants.SOFA_HYSTRIX_ENABLED);
    if (StringUtils.isNotBlank(consumerHystrixEnabled)) {
        return Boolean.valueOf(consumerHystrixEnabled);
    }
    return RpcConfigs.getOrDefaultValue(HystrixConstants.SOFA_HYSTRIX_ENABLED, false);
}
 
Example #7
Source File: BootstrapsTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    oldP = RpcConfigs.getStringValue(RpcOptions.DEFAULT_PROVIDER_BOOTSTRAP);
    oldC = RpcConfigs.getStringValue(RpcOptions.DEFAULT_CONSUMER_BOOTSTRAP);
    RpcConfigs.putValue(RpcOptions.DEFAULT_PROVIDER_BOOTSTRAP, "test");
    RpcConfigs.putValue(RpcOptions.DEFAULT_CONSUMER_BOOTSTRAP, "test");
}
 
Example #8
Source File: Bootstraps.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 引用一个服务
 *
 * @param consumerConfig 服务消费者配置
 * @param <T>            接口类型
 * @return 引用启动类
 */
public static <T> ConsumerBootstrap<T> from(ConsumerConfig<T> consumerConfig) {
    String bootstrap = consumerConfig.getBootstrap();
    ConsumerBootstrap consumerBootstrap;
    if (StringUtils.isNotEmpty(bootstrap)) {
        consumerBootstrap = ExtensionLoaderFactory.getExtensionLoader(ConsumerBootstrap.class)
            .getExtension(bootstrap,
                new Class[] { ConsumerConfig.class },
                new Object[] { consumerConfig });
    } else {
        // default is same with protocol
        bootstrap = consumerConfig.getProtocol();
        ExtensionLoader extensionLoader = ExtensionLoaderFactory.getExtensionLoader(ConsumerBootstrap.class);
        ExtensionClass<ConsumerBootstrap> extensionClass = extensionLoader.getExtensionClass(bootstrap);
        if (extensionClass == null) {
            // if not exist, use default consumer bootstrap
            bootstrap = RpcConfigs.getStringValue(RpcOptions.DEFAULT_CONSUMER_BOOTSTRAP);
            consumerConfig.setBootstrap(bootstrap);
            consumerBootstrap = ExtensionLoaderFactory.getExtensionLoader(ConsumerBootstrap.class)
                .getExtension(bootstrap, new Class[] { ConsumerConfig.class }, new Object[] { consumerConfig });
        } else {
            consumerConfig.setBootstrap(bootstrap);
            consumerBootstrap = extensionClass.getExtInstance(
                new Class[] { ConsumerConfig.class }, new Object[] { consumerConfig });
        }
    }
    return (ConsumerBootstrap<T>) consumerBootstrap;
}
 
Example #9
Source File: Bootstraps.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 发布一个服务
 *
 * @param providerConfig 服务发布者配置
 * @param <T>            接口类型
 * @return 发布启动类
 */
public static <T> ProviderBootstrap<T> from(ProviderConfig<T> providerConfig) {
    String bootstrap = providerConfig.getBootstrap();
    if (StringUtils.isEmpty(bootstrap)) {
        // Use default provider bootstrap
        bootstrap = RpcConfigs.getStringValue(RpcOptions.DEFAULT_PROVIDER_BOOTSTRAP);
        providerConfig.setBootstrap(bootstrap);
    }
    ProviderBootstrap providerBootstrap = ExtensionLoaderFactory.getExtensionLoader(ProviderBootstrap.class)
        .getExtension(bootstrap, new Class[] { ProviderConfig.class }, new Object[] { providerConfig });
    return (ProviderBootstrap<T>) providerBootstrap;
}
 
Example #10
Source File: ServerFactory.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 确定下Server的host和port
 *
 * @param serverConfig 服务器配置
 */
private static void resolveServerConfig(ServerConfig serverConfig) {
    // 绑定到指定网卡 或全部网卡
    String boundHost = serverConfig.getBoundHost();
    if (boundHost == null) {
        String host = serverConfig.getHost();
        if (StringUtils.isBlank(host)) {
            host = SystemInfo.getLocalHost();
            serverConfig.setHost(host);
            // windows绑定到0.0.0.0的某个端口以后,其它进程还能绑定到该端口
            boundHost = SystemInfo.isWindows() ? host : NetUtils.ANYHOST;
        } else {
            boundHost = host;
        }
        serverConfig.setBoundHost(boundHost);
    }

    // 绑定的端口
    if (serverConfig.isAdaptivePort()) {
        int oriPort = serverConfig.getPort();
        int port = NetUtils.getAvailablePort(boundHost, oriPort,
            RpcConfigs.getIntValue(RpcOptions.SERVER_PORT_END));
        if (port != oriPort) {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("Changed port from {} to {} because the config port is disabled", oriPort, port);
            }
            serverConfig.setPort(port);
        }
    }
}
 
Example #11
Source File: RpcRuntimeContext.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 初始化一些上下文
 */
private static void initContext() {
    putIfAbsent(KEY_APPID, RpcConfigs.getOrDefaultValue(APP_ID, null));
    putIfAbsent(KEY_APPNAME, RpcConfigs.getOrDefaultValue(APP_NAME, null));
    putIfAbsent(KEY_APPINSID, RpcConfigs.getOrDefaultValue(INSTANCE_ID, null));
    putIfAbsent(KEY_APPAPTH, System.getProperty("user.dir"));
}
 
Example #12
Source File: ModuleFactory.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * 加载全部模块
 */
public static void installModules() {
    ExtensionLoader<Module> loader = ExtensionLoaderFactory.getExtensionLoader(Module.class);
    String moduleLoadList = RpcConfigs.getStringValue(RpcOptions.MODULE_LOAD_LIST);
    for (Map.Entry<String, ExtensionClass<Module>> o : loader.getAllExtensions().entrySet()) {
        String moduleName = o.getKey();
        Module module = o.getValue().getExtInstance();
        // judge need load from rpc option
        if (needLoad(moduleLoadList, moduleName)) {
            // judge need load from implement
            if (module.needLoad()) {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("Install Module: {}", moduleName);
                }
                module.install();
                INSTALLED_MODULES.put(moduleName, module);
            } else {
                if (LOGGER.isInfoEnabled()) {
                    LOGGER.info("The module " + moduleName + " does not need to be loaded.");
                }
            }
        } else {
            if (LOGGER.isInfoEnabled()) {
                LOGGER.info("The module " + moduleName + " is not in the module load list.");
            }
        }
    }
}
 
Example #13
Source File: InvocationStatDimension.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Gets origin weight.
 *
 * @return the origin weight
 */
public int getOriginWeight() {
    if (originWeight == null) {
        if (providerInfo == null) {
            originWeight = RpcConfigs.getIntValue(RpcOptions.PROVIDER_WEIGHT);
        } else {
            originWeight = CommonUtils.parseInt(providerInfo.getStaticAttr(ProviderInfoAttrs.ATTR_WEIGHT),
                RpcConfigs.getIntValue(RpcOptions.PROVIDER_WEIGHT));
        }
    }
    return originWeight;
}
 
Example #14
Source File: FaultToleranceModule.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Override
public void install() {
    subscriber = new FaultToleranceSubscriber();
    EventBus.register(ClientSyncReceiveEvent.class, subscriber);
    EventBus.register(ClientAsyncReceiveEvent.class, subscriber);
    EventBus.register(ProviderInfoRemoveEvent.class, subscriber);
    EventBus.register(ProviderInfoUpdateEvent.class, subscriber);
    EventBus.register(ProviderInfoUpdateAllEvent.class, subscriber);

    String regulatorAlias = RpcConfigs.getOrDefaultValue(RpcOptions.AFT_REGULATOR, "timeWindow");
    regulator = ExtensionLoaderFactory.getExtensionLoader(Regulator.class).getExtension(regulatorAlias);
    regulator.init();
}
 
Example #15
Source File: AbstractSofaRpcFilter.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Override
public boolean needToLoad(FilterInvoker invoker) {
    AbstractInterfaceConfig<?, ?> config = invoker.getConfig();

    String enabled = config.getParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED);
    if (StringUtils.isNotBlank(enabled)) {
        return Boolean.parseBoolean(enabled);
    }

    return RpcConfigs.getOrDefaultValue(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, true);
}
 
Example #16
Source File: Http2ClearTextHttpUpgradeTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@AfterClass
public static void adAfterClass() {
    ActivelyDestroyTest.adAfterClass();

    /**
     * restore config parameter to previous value
     */
    RpcConfigs.putValue(RpcOptions.TRANSPORT_CLIENT_H2C_USE_PRIOR_KNOWLEDGE, useH2cPriorKnowledge);
}
 
Example #17
Source File: Http2ClearTextHttpUpgradeTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void adBeforeClass() {
    /**
     * set config parameter to using http2 with 'upgrade h2c' startup frame
     */
    RpcConfigs.putValue(RpcOptions.TRANSPORT_CLIENT_H2C_USE_PRIOR_KNOWLEDGE, false);
    ActivelyDestroyTest.adBeforeClass();
}
 
Example #18
Source File: NacosRegistryHelperTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void convertInstancesToProviders() {
    Instance instance = new Instance();
    instance.setClusterName(NacosRegistryHelper.DEFAULT_CLUSTER);
    instance.setIp("1.1.1.1");
    instance.setPort(12200);
    instance.setServiceName("com.alipay.xxx.TestService");

    List<ProviderInfo> providerInfos = NacosRegistryHelper
        .convertInstancesToProviders(Lists.newArrayList(instance));
    assertNotNull(providerInfos);
    assertEquals(1, providerInfos.size());

    ProviderInfo providerInfo = providerInfos.get(0);
    assertNotNull(providerInfo);
    assertEquals(instance.getIp(), providerInfo.getHost());
    assertEquals(instance.getPort(), providerInfo.getPort());

    assertEquals(RpcConfigs.getStringValue(RpcOptions.DEFAULT_PROTOCOL), providerInfo.getProtocolType());

    Map<String, String> metaData = Maps.newHashMap();
    metaData.put(RpcConstants.CONFIG_KEY_PROTOCOL, RpcConstants.PROTOCOL_TYPE_REST);
    instance.setMetadata(metaData);

    providerInfos = NacosRegistryHelper.convertInstancesToProviders(Lists.newArrayList(instance));
    providerInfo = providerInfos.get(0);
    assertEquals(RpcConstants.PROTOCOL_TYPE_REST, providerInfo.getProtocolType());
}
 
Example #19
Source File: SofaHessianSerializer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
/**
 * Instantiates a new Sofa hessian serializer.
 */
public SofaHessianSerializer() {
    try {
        ClassUtils.forName("com.caucho.hessian.io.ShortHandle");
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Version of sofa-hessian is v4.x");
        }
    } catch (Exception e) {
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Version of sofa-hessian is v3.x");
        }
    }
    boolean enableMultipleClassLoader = RpcConfigs.getBooleanValue(RpcOptions.MULTIPLE_CLASSLOADER_ENABLE);
    serializerFactory = getSerializerFactory(enableMultipleClassLoader, false);
    genericSerializerFactory = getSerializerFactory(enableMultipleClassLoader, true);
    if (RpcConfigs.getBooleanValue(RpcOptions.SERIALIZE_BLACKLIST_ENABLE) &&
        SofaConfigs.getBooleanValue(SofaOptions.CONFIG_SERIALIZE_BLACKLIST, true)) {
        ClassNameResolver resolver = new ClassNameResolver();
        resolver.addFilter(new NameBlackListFilter(BlackListFileLoader.SOFA_SERIALIZE_BLACK_LIST, 8192));
        serializerFactory.setClassNameResolver(resolver);
        genericSerializerFactory.setClassNameResolver(resolver);
    } else {
        serializerFactory.setClassNameResolver(null);
        genericSerializerFactory.setClassNameResolver(null);
    }
    CustomHessianSerializerManager.addSerializer(SofaRequest.class,
        new SofaRequestHessianSerializer(serializerFactory, genericSerializerFactory));
    CustomHessianSerializerManager.addSerializer(SofaResponse.class,
        new SofaResponseHessianSerializer(serializerFactory, genericSerializerFactory));
}
 
Example #20
Source File: ApplicationEnvironmentPreparedListener.java    From sofa-rpc-boot-projects with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
    if (event instanceof ApplicationEnvironmentPreparedEvent) {
        Environment env = ((ApplicationEnvironmentPreparedEvent) event).getEnvironment();
        String defaultTracer = env.getProperty(SofaBootRpcProperties.PREFIX + ".defaultTracer");
        if (defaultTracer != null) {
            RpcConfigs.putValue(RpcOptions.DEFAULT_TRACER, defaultTracer);
        }
    }
}
 
Example #21
Source File: AbstractSofaRpcFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void removeRpcConfig(String key) {
    try {
        Method removeValueMethod = RpcConfigs.class.getDeclaredMethod("removeValue", String.class);
        removeValueMethod.setAccessible(true);
        removeValueMethod.invoke(null, key);
    } catch (Exception e) {
        // Empty
    }
}
 
Example #22
Source File: AbstractSofaRpcFilterTest.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
@Test
public void testNeedToLoadProviderAndConsumer() {
    SentinelSofaRpcProviderFilter providerFilter = new SentinelSofaRpcProviderFilter();
    ProviderConfig providerConfig = new ProviderConfig();
    providerConfig.setInterfaceId(Serializer.class.getName());
    providerConfig.setId("AAA");
    FilterInvoker providerInvoker = new FilterInvoker(null, null, providerConfig);
    assertTrue(providerFilter.needToLoad(providerInvoker));

    SentinelSofaRpcConsumerFilter consumerFilter = new SentinelSofaRpcConsumerFilter();
    ConsumerConfig consumerConfig = new ConsumerConfig();
    consumerConfig.setInterfaceId(Serializer.class.getName());
    consumerConfig.setId("BBB");
    FilterInvoker consumerInvoker = new FilterInvoker(null, null, consumerConfig);
    assertTrue(consumerFilter.needToLoad(consumerInvoker));

    providerConfig.setParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "false");
    assertFalse(providerFilter.needToLoad(providerInvoker));
    assertTrue(consumerFilter.needToLoad(consumerInvoker));

    providerConfig.setParameter(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "");
    assertTrue(providerFilter.needToLoad(providerInvoker));

    RpcConfigs.putValue(SentinelConstants.SOFA_RPC_SENTINEL_ENABLED, "false");
    assertFalse(providerFilter.needToLoad(providerInvoker));
    assertFalse(consumerFilter.needToLoad(consumerInvoker));
}
 
Example #23
Source File: FailoverClusterTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test(expected = SofaRouteException.class)
public void testRpcDirectInvokeFromContextNotAllowed() {

    boolean prev = RpcConfigs.getBooleanValue(RpcOptions.RPC_CREATE_CONN_WHEN_ABSENT);

    // disable create connection from context
    RpcConfigs.putValue(RpcOptions.RPC_CREATE_CONN_WHEN_ABSENT, false);

    try {
        ServerConfig serverConfig = new ServerConfig()
            .setProtocol("bolt")
            .setHost("0.0.0.0")
            .setPort(13900);

        ProviderConfig<HelloService> provider = new ProviderConfig();
        provider.setInterfaceId(HelloService.class.getName())
            .setRef(new HelloServiceImpl("x-demo-invoke"))
            .setApplication(new ApplicationConfig().setAppName("x-test-server"))
            .setProxy("javassist")
            .setSerialization("hessian2")
            .setServer(serverConfig)
            .setTimeout(3000);

        provider.export();

        ConsumerConfig<HelloService> consumer = new ConsumerConfig();
        consumer.setInterfaceId(HelloService.class.getName())
            .setApplication(new ApplicationConfig().setAppName("x-test-client"))
            .setProxy("javassist");

        HelloService proxy = consumer.refer();

        RpcInvokeContext.getContext().setTargetURL("127.0.0.1:13900");
        proxy.sayHello("x-demo-invoke", 1);

        provider.unExport();
        consumer.unRefer();
    } finally {
        RpcConfigs.putValue(RpcOptions.RPC_CREATE_CONN_WHEN_ABSENT, prev);
    }
}
 
Example #24
Source File: AsyncRuntime.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
/**
 * 得到callback用的线程池
 *
 * @param build 没有时是否构建
 * @return callback用的线程池
 */
public static ThreadPoolExecutor getAsyncThreadPool(boolean build) {
    if (asyncThreadPool == null && build) {
        synchronized (AsyncRuntime.class) {
            if (asyncThreadPool == null && build) {
                // 一些系统参数,可以从配置或者注册中心获取。
                int coresize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_CORE);
                int maxsize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_MAX);
                int queuesize = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_QUEUE);
                int keepAliveTime = RpcConfigs.getIntValue(RpcOptions.ASYNC_POOL_TIME);

                BlockingQueue<Runnable> queue = ThreadPoolUtils.buildQueue(queuesize);
                NamedThreadFactory threadFactory = new NamedThreadFactory("RPC-CB", true);

                RejectedExecutionHandler handler = new RejectedExecutionHandler() {
                    private int i = 1;

                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        if (i++ % 7 == 0) {
                            i = 1;
                            if (LOGGER.isWarnEnabled()) {
                                LOGGER.warn("Task:{} has been reject because of threadPool exhausted!" +
                                    " pool:{}, active:{}, queue:{}, taskcnt: {}", r,
                                    executor.getPoolSize(),
                                    executor.getActiveCount(),
                                    executor.getQueue().size(),
                                    executor.getTaskCount());
                            }
                        }
                        throw new RejectedExecutionException(
                            LogCodes.getLog(LogCodes.ERROR_ASYNC_THREAD_POOL_REJECT));
                    }
                };
                asyncThreadPool = ThreadPoolUtils.newCachedThreadPool(
                    coresize, maxsize, keepAliveTime, queue, threadFactory, handler);
            }
        }
    }
    return asyncThreadPool;
}
 
Example #25
Source File: ModuleFactoryTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testAll() throws Exception {
    String old = RpcConfigs.getStringValue(RpcOptions.MODULE_LOAD_LIST);
    try {
        RpcConfigs.putValue(RpcOptions.MODULE_LOAD_LIST, "*,-test3");

        ModuleFactory.installModules();
        Assert.assertFalse(ModuleFactory.INSTALLED_MODULES.isEmpty());
        Assert.assertTrue(ModuleFactory.INSTALLED_MODULES.containsKey("test"));
        Assert.assertTrue(ModuleFactory.INSTALLED_MODULES.containsKey("test2"));
        Assert.assertFalse(ModuleFactory.INSTALLED_MODULES.containsKey("testNot"));
        Assert.assertEquals("testi", TestModules.test);
        Assert.assertEquals("test2i", TestModules.test2);
        Assert.assertNull(TestModules.testNot);

        TestModules.error = true;
        ModuleFactory.uninstallModule("test");
        Assert.assertTrue(ModuleFactory.INSTALLED_MODULES.containsKey("test"));
        TestModules.error = false;

        TestModules.error = false;
        ModuleFactory.uninstallModule("test");
        Assert.assertFalse(ModuleFactory.INSTALLED_MODULES.containsKey("test"));
        Assert.assertTrue(ModuleFactory.INSTALLED_MODULES.containsKey("test2"));
        Assert.assertEquals("testu", TestModules.test);
        Assert.assertEquals("test2i", TestModules.test2);
        Assert.assertNull(TestModules.testNot);

        TestModules.error = true;
        ModuleFactory.uninstallModules();
        Assert.assertTrue(ModuleFactory.INSTALLED_MODULES.containsKey("test2"));
        TestModules.error = false;

        ModuleFactory.uninstallModules();
        Assert.assertTrue(ModuleFactory.INSTALLED_MODULES.isEmpty());
        Assert.assertEquals("testu", TestModules.test);
        Assert.assertEquals("test2u", TestModules.test2);
        Assert.assertNull(TestModules.testNot);
    } finally {
        if (old != null) {
            RpcConfigs.putValue(RpcOptions.MODULE_LOAD_LIST, old);
        }
    }
}
 
Example #26
Source File: EventBusTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void isEnable() throws Exception {
    Assert.assertEquals(EventBus.isEnable(), RpcConfigs.getBooleanValue(RpcOptions.EVENT_BUS_ENABLE));
}
 
Example #27
Source File: BootstrapsTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@After
public void after() {
    RpcConfigs.putValue(RpcOptions.DEFAULT_PROVIDER_BOOTSTRAP, oldP);
    RpcConfigs.putValue(RpcOptions.DEFAULT_CONSUMER_BOOTSTRAP, oldC);
}
 
Example #28
Source File: ZookeeperRegistryHelper.java    From sofa-rpc with Apache License 2.0 3 votes vote down vote up
/**
 * Convert child data to attribute.
 *
 * @param configPath the config path
 * @param childData  the child data
 * @param removeType is remove type
 * @return the attribute
 */
static Map<String, String> convertConfigToAttribute(String configPath, ChildData childData,
                                                    boolean removeType) {
    String attribute = childData.getPath().substring(configPath.length() + 1);
    //If event type is CHILD_REMOVED, attribute should return to default value
    return Collections.singletonMap(attribute, removeType ? RpcConfigs.getStringValue(attribute)
        : StringSerializer.decode(childData.getData()));
}
 
Example #29
Source File: SofaTracerModule.java    From sofa-rpc with Apache License 2.0 2 votes vote down vote up
/**
 * 是否启动Tracer
 *
 * @return 是否开启
 */
public static boolean isEnable() {
    String traceName = RpcConfigs.getStringValue(RpcOptions.DEFAULT_TRACER);
    return "sofaTracer".equals(traceName);
}