Java Code Examples for com.alipay.sofa.rpc.config.ProviderConfig#export()

The following examples show how to use com.alipay.sofa.rpc.config.ProviderConfig#export() . 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: LazyConnectTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void startServer() {

    RpcRunningState.setUnitTestMode(true);
    // 只有2个线程 执行
    serverConfig = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22222)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);

    // 发布一个服务,每个请求要执行1秒
    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl())
        .setServer(serverConfig)
        .setRegister(false);
    providerConfig.export();
}
 
Example 2
Source File: CustomFilterServerMain.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        Filter customEchoFilter2 = new CustomEchoFilter2();

        ApplicationConfig application = new ApplicationConfig().setAppName("test-server");

        ServerConfig serverConfig = new ServerConfig()
            .setPort(22000)
            .setDaemon(false);

        ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
            .setInterfaceId(HelloService.class.getName())
            .setApplication(application)
            .setRef(new HelloServiceImpl())
            .setServer(serverConfig)
            .setFilter(Arrays.asList("customEcho"))
            .setFilterRef(Arrays.asList(customEchoFilter2))
            .setRegister(false);

        providerConfig.export();

        LOGGER.error("started at pid {}", RpcRuntimeContext.PID);
    }
 
Example 3
Source File: LocalBoltServerMain.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        String file = System.getProperty("user.home") + File.separator
            + "localFileTest" + File.separator + "localRegistry.reg";

        RegistryConfig registryConfig = new RegistryConfig().setProtocol("local")
            .setFile(file);

        ServerConfig serverConfig = new ServerConfig()
            .setPort(22222)
            .setDaemon(false);

        ServerConfig serverConfig2 = new ServerConfig()
            .setPort(22200)
            .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
            .setDaemon(false);

        ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
            .setInterfaceId(HelloService.class.getName())
            .setRef(new HelloServiceImpl())
            .setServer(serverConfig)
            .setRegistry(registryConfig);

        ProviderConfig<EchoService> providerConfig2 = new ProviderConfig<EchoService>()
            .setInterfaceId(EchoService.class.getName())
            .setRef(new EchoServiceImpl())
            .setServer(serverConfig)
            .setRegistry(registryConfig);

        providerConfig.export();
        providerConfig2.export();

        LOGGER.warn("started at pid {}", RpcRuntimeContext.PID);
    }
 
Example 4
Source File: SofaRegistryServer.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    /**
     * 运行时项目引入依赖
     <dependency>
         <groupId>com.alipay.sofa</groupId>
         <artifactId>registry-client-all</artifactId>
         <version>5.2.0</version>
     </dependency>
     */
    RegistryConfig registryConfig = new RegistryConfig()
        .setProtocol(RpcConstants.REGISTRY_PROTOCOL_SOFA)
        .setAddress("127.0.0.1:9603");

    ServerConfig serverConfig = new ServerConfig()
        .setProtocol("bolt")
        .setPort(12200)
        .setDaemon(false);

    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setRegistry(registryConfig)
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl())
        .setServer(serverConfig);

    providerConfig.export();
    LOGGER.warn("started at pid {}", RpcRuntimeContext.PID);
}
 
Example 5
Source File: ServerC.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ServerConfig serverConfig = new ServerConfig()
        .setPort(12299)
        .setDaemon(false);

    ProviderConfig<ServiceC> providerConfig = new ProviderConfig<ServiceC>()
        .setInterfaceId(ServiceC.class.getName())
        .setApplication(new ApplicationConfig().setAppName("CCC"))
        .setRef(new ServiceCImpl(1000))
        .setServer(serverConfig)
        .setRegister(false);

    providerConfig.export();
}
 
Example 6
Source File: ZookeeperBoltServerMain.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {

        /**
         * 运行需要pom.xml里增加依赖 
         <dependency>
             <groupId>org.apache.curator</groupId>
             <artifactId>curator-recipes</artifactId>
             <scope>test</scope>
         </dependency>
         */
        RegistryConfig registryConfig = new RegistryConfig()
            .setProtocol(RpcConstants.REGISTRY_PROTOCOL_ZK)
            .setAddress("127.0.0.1:2181");

        ServerConfig serverConfig = new ServerConfig()
            .setPort(22101)
            .setDaemon(false);

        ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
            .setInterfaceId(HelloService.class.getName())
            .setRef(new HelloServiceImpl("result from 22101"))
            .setServer(serverConfig)
            .setRegistry(registryConfig);

        ProviderConfig<EchoService> providerConfig2 = new ProviderConfig<EchoService>()
            .setInterfaceId(EchoService.class.getName())
            .setRef(new EchoServiceImpl())
            .setServer(serverConfig)
            .setRegistry(registryConfig);

        providerConfig.export();
        providerConfig2.export();

        LOGGER.warn("started at pid {}", RpcRuntimeContext.PID);
    }
 
Example 7
Source File: SofaRpcApplication.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Bean(destroyMethod = "unExport")
public ProviderConfig provider() {
    ServerConfig config = new ServerConfig().setProtocol("bolt").setPort(12200).setDaemon(true);

    ProviderConfig<SofaRpcDemoService> providerConfig = new ProviderConfig<SofaRpcDemoService>().setInterfaceId(SofaRpcDemoService.class
        .getName()).setRef(new SofaRpcDemoServiceImpl()).setServer(config);

    providerConfig.export();
    return providerConfig;
}
 
Example 8
Source File: BoltProtobufTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testAll() {
    ServerConfig serverConfig = new ServerConfig()
        .setProtocol("bolt") // 设置一个协议,默认bolt
        .setPort(12200) // 设置一个端口,默认12200
        .setDaemon(false); // 非守护线程

    ProviderConfig<ProtobufService> providerConfig = new ProviderConfig<ProtobufService>()
        .setInterfaceId(ProtobufService.class.getName()) // 指定接口
        .setRef(new ProtobufServiceImpl()) // 指定实现
        .setServer(serverConfig); // 指定服务端
    providerConfig.export(); // 发布服务

    ConsumerConfig<ProtobufService> consumerConfig = new ConsumerConfig<ProtobufService>()
        .setInterfaceId(ProtobufService.class.getName()) // 指定接口
        .setProtocol("bolt") // 指定协议
        .setDirectUrl("bolt://127.0.0.1:12200") // 指定直连地址
        .setSerialization("protobuf") // 指定序列化协议,默认为hessian
        .setConnectTimeout(10 * 1000);
    ProtobufService helloService = consumerConfig.refer();

    EchoRequest request = EchoRequest.newBuilder().setName("sofa").setGroup(Group.A).build();
    EchoResponse response = helloService.echoObj(request);
    LOGGER.info(response.getCode() + ": " + response.getMessage());

    boolean error = false;
    try {
        helloService.echoObj(null);
    } catch (Exception e) {
        error = true;
    }
    Assert.assertTrue(error);

    Assert.assertEquals(200, response.getCode());
    Assert.assertEquals("protobuf works! sofa", response.getMessage());
}
 
Example 9
Source File: GenericServerMain.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    ApplicationConfig applicationConfig = new ApplicationConfig().setAppName("generic-server");

    ServerConfig serverConfig2 = new ServerConfig()
        .setPort(22222)
        .setDaemon(false);

    ProviderConfig<TestGenericService> providerConfig = new ProviderConfig<TestGenericService>()
        .setApplication(applicationConfig)
        .setInterfaceId(TestGenericService.class.getName())
        .setRef(new TestGenericServiceImpl())
        .setServer(serverConfig2);
    providerConfig.export();
}
 
Example 10
Source File: Http2ServerMain.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ApplicationConfig application = new ApplicationConfig().setAppName("test-server");

    ServerConfig serverConfig = new ServerConfig()
        .setProtocol("h2c")
        .setPort(12300)
        .setDaemon(false);

    ProviderConfig<ProtoService> providerConfig = new ProviderConfig<ProtoService>()
        .setInterfaceId(ProtoService.class.getName())
        .setApplication(application)
        .setRef(new ProtoServiceImpl())
        .setServer(serverConfig);

    providerConfig.export();

    ProviderConfig<HelloService> providerConfig2 = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setApplication(application)
        .setRef(new HelloServiceImpl())
        .setServer(serverConfig)
        .setRegister(false);
    providerConfig2.export();
    // http://127.0.0.1:12300/com.alipay.sofa.rpc.test.HelloService/sayHello

    LOGGER.error("started at pid {}", RpcRuntimeContext.PID);

    final AtomicInteger cnt = ((ProtoServiceImpl) providerConfig.getRef()).getCounter();
    final ThreadPoolExecutor executor = ((Http2ClearTextServer) serverConfig.getServer()).getBizThreadPool();
    Thread thread = new Thread(new Runnable() {
        private long last = 0;

        @Override
        public void run() {
            while (true) {
                long count = cnt.get();
                long tps = count - last;
                LOGGER.error("last 1s invoke: {}, queue: {}", tps, executor.getQueue().size());
                last = count;

                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            }
        }
    }, "Print-tps-THREAD");
    thread.start();
}
 
Example 11
Source File: SyncFilterTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void test() {
    ServerConfig serverConfig2 = new ServerConfig()
        .setPort(22222)
        .setDaemon(false);

    // ProviderConfig
    TestSyncFilter filter1 = new TestSyncFilter();
    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl(1000))
        .setFilterRef(Arrays.asList((Filter) filter1))
        .setApplication(new ApplicationConfig().setAppName("sss"))
        .setServer(serverConfig2);

    providerConfig.export();

    // ConsumerConfig
    TestSyncFilter filter0 = new TestSyncFilter();
    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setInvokeType(RpcConstants.INVOKER_TYPE_SYNC)
        .setApplication(new ApplicationConfig().setAppName("ccc"))
        .setTimeout(5000)
        .setFilterRef(Arrays.asList((Filter) filter0))
        .setDirectUrl("bolt://127.0.0.1:22222?appName=sss");
    HelloService helloService = consumerConfig.refer();

    try {
        helloService.sayHello("xxx", 12);
        // Consumer side
        Assert.assertEquals("xxx", filter0.args[0]);
        Assert.assertEquals(12, filter0.args[1]);
        Assert.assertEquals(HelloService.class.getName(), filter0.interfaceName);
        Assert.assertEquals("com.alipay.sofa.rpc.test.HelloService:1.0", filter0.targetServiceUniqueName);
        Assert.assertEquals("sayHello", filter0.methodName);
        Assert.assertEquals(RpcConstants.INVOKER_TYPE_SYNC, filter0.invokeType);
        Assert.assertNull(filter0.targetAppName);

        // Provider side
        Assert.assertEquals("xxx", filter1.args[0]);
        Assert.assertEquals(12, filter1.args[1]);
        Assert.assertEquals(HelloService.class.getName(), filter1.interfaceName);
        Assert.assertEquals("com.alipay.sofa.rpc.test.HelloService:1.0", filter1.targetServiceUniqueName);
        Assert.assertEquals("sayHello", filter1.methodName);
        Assert.assertEquals("sss", filter1.targetAppName);
    } catch (Exception e) {
    }
}
 
Example 12
Source File: BoltProtobufBaggageSyncTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Override
void doTest() {
    ServerConfig serverConfig = new ServerConfig().setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT).setPort(12299);

    // C服务的服务端
    CSampleServiceImpl refC = new CSampleServiceImpl();
    ProviderConfig<SampleService> serviceBeanC = new ProviderConfig<SampleService>();
    serviceBeanC.setInterfaceId(SampleService.class.getName());
    serviceBeanC.setApplication(new ApplicationConfig().setAppName("CCC"));
    serviceBeanC.setUniqueId("C1");
    serviceBeanC.setRef(refC);
    serviceBeanC.setServer(serverConfig);
    serviceBeanC.setRegister(false);
    serviceBeanC.export();

    // D服务的服务端
    DSampleServiceImpl refD = new DSampleServiceImpl();
    ProviderConfig<SampleService> serviceBeanD = new ProviderConfig<SampleService>();
    serviceBeanD.setInterfaceId(SampleService.class.getName());
    serviceBeanD.setApplication(new ApplicationConfig().setAppName("DDD"));
    serviceBeanD.setUniqueId("D1");
    serviceBeanD.setRef(refD);
    serviceBeanD.setServer(serverConfig);
    serviceBeanD.setRegister(false);
    serviceBeanD.export();

    // B服务里的C服务客户端
    ConsumerConfig referenceBeanC = new ConsumerConfig();
    referenceBeanC.setApplication(new ApplicationConfig().setAppName("BBB"));
    referenceBeanC.setInterfaceId(SampleService.class.getName());
    referenceBeanC.setUniqueId("C1");
    referenceBeanC.setDirectUrl("localhost:12299");
    referenceBeanC.setSerialization("protobuf");
    referenceBeanC.setTimeout(1000);
    SampleService sampleServiceC = (SampleService) referenceBeanC.refer();

    // B服务里的D服务客户端
    ConsumerConfig referenceBeanD = new ConsumerConfig();
    referenceBeanD.setApplication(new ApplicationConfig().setAppName("BBB"));
    referenceBeanD.setInterfaceId(SampleService.class.getName());
    referenceBeanD.setUniqueId("D1");
    referenceBeanD.setDirectUrl("localhost:12299?p=1&v=4.0");
    referenceBeanD.setSerialization("protobuf");
    referenceBeanD.setTimeout(1000);
    SampleService sampleServiceD = (SampleService) referenceBeanD.refer();

    // B服务的服务端
    BSampleServiceImpl refB = new BSampleServiceImpl(sampleServiceC, sampleServiceD);
    ProviderConfig<SampleService> ServiceBeanB = new ProviderConfig<SampleService>();
    ServiceBeanB.setInterfaceId(SampleService.class.getName());
    ServiceBeanB.setApplication(new ApplicationConfig().setAppName("BBB"));
    ServiceBeanB.setUniqueId("B1");
    ServiceBeanB.setRef(refB);
    ServiceBeanB.setServer(serverConfig);
    ServiceBeanB.setRegister(false);
    ServiceBeanB.export();

    // A 服务
    ConsumerConfig referenceBeanA = new ConsumerConfig();
    referenceBeanA.setApplication(new ApplicationConfig().setAppName("AAA"));
    referenceBeanA.setUniqueId("B1");
    referenceBeanA.setInterfaceId(SampleService.class.getName());
    referenceBeanA.setDirectUrl("localhost:12299");
    referenceBeanA.setSerialization("protobuf");
    referenceBeanA.setTimeout(3000);

    SampleService service = (SampleService) referenceBeanA.refer();

    // 开始测试
    RpcInvokeContext context = RpcInvokeContext.getContext();
    context.putRequestBaggage("reqBaggageB", "a2bbb");
    context.putRequestBaggage("reqBaggageC", "a2ccc");
    context.putRequestBaggage("reqBaggageD", "a2ddd");
    EchoRequest request = EchoRequest.newBuilder().setGroup(Group.A).setName("xxx").build();
    EchoResponse ret = service.echoObj(request);
    Assert.assertEquals(ret.getMessage(), "hello world chello world d");
    Assert.assertEquals(refB.getReqBaggage(), "a2bbb");
    Assert.assertEquals(refC.getReqBaggage(), "a2ccc");
    Assert.assertEquals(refD.getReqBaggage(), "a2ddd");

    Assert.assertEquals(context.getResponseBaggage("respBaggageB"), "b2aaa");
    Assert.assertEquals(context.getResponseBaggage("respBaggageC"), "c2aaa");
    Assert.assertEquals(context.getResponseBaggage("respBaggageD"), "d2aaa");
    Assert.assertNull(context.getResponseBaggage("respBaggageB_force"));
    Assert.assertNull(context.getResponseBaggage("respBaggageC_force"));
    Assert.assertNull(context.getResponseBaggage("respBaggageD_force"));

    RpcInvokeContext.removeContext();
    context = RpcInvokeContext.getContext();
    ret = service.echoObj(request);
    Assert.assertEquals(ret.getMessage(), "hello world chello world d");
    Assert.assertNull(refB.getReqBaggage());
    Assert.assertNull(refC.getReqBaggage());
    Assert.assertNull(refD.getReqBaggage());
    Assert.assertNull(context.getResponseBaggage("respBaggageB"));
    Assert.assertNull(context.getResponseBaggage("respBaggageC"));
    Assert.assertNull(context.getResponseBaggage("respBaggageD"));
    Assert.assertEquals(context.getResponseBaggage("respBaggageB_force"), "b2aaaff");
    Assert.assertEquals(context.getResponseBaggage("respBaggageC_force"), "c2aaaff");
    Assert.assertEquals(context.getResponseBaggage("respBaggageD_force"), "d2aaaff");
}
 
Example 13
Source File: RestDirectUrlTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testAll() {

    // 只有1个线程 执行
    ServerConfig serverConfig = new ServerConfig()
        .setPort(12300)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST)
        .setDaemon(true);

    // 发布一个服务,每个请求要执行1秒
    ProviderConfig<RestService> providerConfig = new ProviderConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setRef(new RestServiceImpl())
        .setBootstrap("rest")
        .setApplication(new ApplicationConfig().setAppName("serverApp"))
        .setServer(serverConfig)
        .setRegister(false);
    providerConfig.export();

    final ConsumerConfig<RestService> consumerConfig = new ConsumerConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setDirectUrl("rest://127.0.0.1:12300")
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST)
        .setBootstrap("rest")
        .setApplication(new ApplicationConfig().setAppName("clientApp"))
        .setReconnectPeriod(1000);

    RestService restService = consumerConfig.refer();

    Assert.assertEquals(restService.query(11), "hello world !null");

    serverConfig.getServer().stop();

    // 关闭后再调用一个抛异常
    try {
        restService.query(11);
    } catch (Exception e) {
        // 应该抛出异常
        Assert.assertTrue(e instanceof SofaRpcException);
    }

    Assert.assertTrue(TestUtils.delayGet(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return CommonUtils.isEmpty(consumerConfig.getConsumerBootstrap()
                .getCluster().getConnectionHolder().getAvailableConnections());
        }
    }, true, 50, 40));

    serverConfig.getServer().start();
    // 等待客户端重连服务端
    Assert.assertTrue(TestUtils.delayGet(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return CommonUtils.isNotEmpty(consumerConfig.getConsumerBootstrap()
                .getCluster().getConnectionHolder().getAvailableConnections());
        }
    }, true, 50, 60));

    Assert.assertEquals(restService.query(11), "hello world !null");
}
 
Example 14
Source File: DiscardTimeoutTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testAll() {

    ServerConfig serverConfig = new ServerConfig()
        .setStopTimeout(0).setPort(22222)
        .setQueues(5).setCoreThreads(1).setMaxThreads(1);

    // 发布一个服务,每个请求要执行2秒
    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl(2000))
        .setServer(serverConfig)
        .setRegister(false);
    providerConfig.export();

    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setTimeout(5000)
        .setDirectUrl("bolt://127.0.0.1:22222")
        .setRegister(false);

    final HelloService helloService = consumerConfig.refer();

    final AtomicInteger success = new AtomicInteger();
    final AtomicInteger failure = new AtomicInteger();

    int times = 4;
    final CountDownLatch latch = new CountDownLatch(times);
    for (int i = 0; i < times; i++) {
        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    helloService.sayHello("xxx", 22);
                    success.incrementAndGet();
                } catch (Exception e) {
                    failure.incrementAndGet();
                    Assert.assertTrue(e instanceof SofaRpcException);
                    Assert.assertTrue(((SofaRpcException) e).getErrorType() == RpcErrorType.CLIENT_TIMEOUT);
                } finally {
                    latch.countDown();
                }
            }
        }, "T1");
        thread1.start();
    }

    try {
        latch.await(10000, TimeUnit.MILLISECONDS); // 此时客户端提前抛出超时异常
    } catch (InterruptedException ignore) {
    }
    // 2秒1个 超时3秒  超时3个
    // 第一个请求正常
    // 第二个请求返回时超时
    // 第三个请求返回时超时
    // 第四个请求已超时
    Assert.assertEquals(success.get(), 2);
    Assert.assertEquals(failure.get(), 2);
}
 
Example 15
Source File: RestProviderTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testProvider() {
    JAXRSProviderManager.registerCustomProviderInstance(new CustomerInjectorFactory());
    JAXRSProviderManager.registerCustomProviderInstance(new ClientRequestTestFilter());
    JAXRSProviderManager.registerCustomProviderInstance(new ClientRequestTestFilter2());
    JAXRSProviderManager.registerCustomProviderInstance(new ContainerRequestTestFilter());
    JAXRSProviderManager.registerCustomProviderInstance(new ContainerResponseTestFilter());
    JAXRSProviderManager.registerCustomProviderInstance(new ClientResponseTestFilter());

    ServerConfig serverConfig = new ServerConfig()
        .setStopTimeout(60000)
        .setPort(8803)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST);

    ProviderConfig<RestService> providerConfig = new ProviderConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setRef(new RestServiceImpl())
        .setServer(serverConfig)
        .setBootstrap("rest")
        .setRegister(false);
    providerConfig.export();

    ConsumerConfig<RestService> consumerConfig = new ConsumerConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setDirectUrl("rest://127.0.0.1:8803")
        .setProtocol("rest")
        .setBootstrap("rest")
        .setTimeout(30000)
        .setRegister(false)
        .setFilter(Arrays.asList("-*"))
        .setApplication(new ApplicationConfig().setAppName("TestClient"));
    RestService restService = consumerConfig.refer();

    Assert.assertEquals("serverok", restService.get("ok"));

    String nameA = ClientRequestTestFilter.getName();
    String nameA2 = ClientRequestTestFilter2.getName();
    String nameB = ContainerRequestTestFilter.getName();
    String nameC = ContainerResponseTestFilter.getName();
    String nameD = ClientResponseTestFilter.getName();
    Assert.assertEquals("AtestInjecttestInject", nameA);
    Assert.assertEquals("A2", nameA2);
    Assert.assertEquals("B", nameB);
    Assert.assertEquals("C", nameC);
    Assert.assertEquals("D", nameD);

}
 
Example 16
Source File: H2cDirectUrlTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testAll() throws InterruptedException {

    // 只有1个线程 执行
    ServerConfig serverConfig = new ServerConfig()
        .setPort(12300)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_H2C)
        .setDaemon(true);

    // 发布一个服务,每个请求要执行1秒
    ProviderConfig<HttpService> providerConfig = new ProviderConfig<HttpService>()
        .setInterfaceId(HttpService.class.getName())
        .setRef(new HttpServiceImpl())
        .setBootstrap("h2c")
        .setApplication(new ApplicationConfig().setAppName("serverApp"))
        .setServer(serverConfig)
        .setRegister(false);
    providerConfig.export();

    final ConsumerConfig<HttpService> consumerConfig = new ConsumerConfig<HttpService>()
        .setInterfaceId(HttpService.class.getName())
        .setDirectUrl("h2c://127.0.0.1:12300")
        .setProtocol(RpcConstants.PROTOCOL_TYPE_H2C)
        .setBootstrap("h2c")
        .setApplication(new ApplicationConfig().setAppName("clientApp"))
        .setReconnectPeriod(1000);

    HttpService httpService = consumerConfig.refer();

    ExampleObj request = new ExampleObj();
    request.setId(200);
    request.setName("yyy");
    ExampleObj response = httpService.object(request);
    Assert.assertEquals(200, response.getId());
    Assert.assertEquals("yyyxx", response.getName());

    serverConfig.getServer().stop();

    // 关闭后再调用一个抛异常
    try {
        httpService.object(request);
    } catch (Exception e) {
        // 应该抛出异常
        Assert.assertTrue(e instanceof SofaRpcException);
    }

    Assert.assertTrue(TestUtils.delayGet(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return CommonUtils.isEmpty(consumerConfig.getConsumerBootstrap()
                .getCluster().getConnectionHolder().getAvailableConnections());
        }
    }, true, 50, 40));

    serverConfig.getServer().start();
    // 等待客户端重连服务端
    Assert.assertTrue(TestUtils.delayGet(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return CommonUtils.isNotEmpty(consumerConfig.getConsumerBootstrap()
                .getCluster().getConnectionHolder().getAvailableConnections());
        }
    }, true, 50, 60));

    response = httpService.object(request);
    Assert.assertEquals(200, response.getId());
    Assert.assertEquals("yyyxx", response.getName());
}
 
Example 17
Source File: DubboServerMain.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
public static void main(String[] args) {
    ApplicationConfig applicationConfig = new ApplicationConfig().setAppName("dubbo-server");

    ServerConfig serverConfig = new ServerConfig()
        .setProtocol("dubbo")
        .setHost("127.0.0.1")
        .setPort(20080)
        .setSerialization("hessian2")
        .setDaemon(false);

    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setBootstrap("dubbo")
        .setApplication(applicationConfig)
        .setRef(new HelloServiceImpl())
        .setUniqueId("xxx")
        .setServer(serverConfig)
        .setRegister(false);

    ProviderConfig<EchoService> providerConfig2 = new ProviderConfig<EchoService>()
        .setInterfaceId(EchoService.class.getName())
        .setRef(new EchoServiceImpl())
        .setApplication(applicationConfig)
        .setBootstrap("dubbo")
        .setUniqueId("xxx")
        .setServer(serverConfig)
        .setRegister(false);

    providerConfig.export();
    providerConfig2.export();

    LOGGER.warn("started at pid {}", RpcRuntimeContext.PID);

    synchronized (DubboServerMain.class) {
        while (true) {
            try {
                DubboServerMain.class.wait();
            } catch (InterruptedException e) {

            }
        }
    }
}
 
Example 18
Source File: RestTracerTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testRestTracer() throws InterruptedException, IOException {

    Reporter clientReporter = reflectToTracer();
    memoryReporter = (MemoryReporterImpl) clientReporter;

    ServerConfig restServer = new ServerConfig()
        .setPort(8583)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST);

    List<ServerConfig> servers = new ArrayList<ServerConfig>(2);
    servers.add(restServer);

    ProviderConfig<RestService> providerConfig = new ProviderConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setRef(new RestServiceImpl())
        .setRegister(false)
        .setServer(servers);
    providerConfig.export();

    //rest服务
    ConsumerConfig<RestService> consumerConfigRest = new ConsumerConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST)
        .setDirectUrl("rest://127.0.0.1:8583")
        .setTimeout(1000)
        .setApplication(new ApplicationConfig().setAppName("TestClientRest"));
    final RestService restServiceRest = consumerConfigRest.refer();

    restServiceRest.get("test");

    final int times = 10;
    final CountDownLatch latch = new CountDownLatch(times);
    final AtomicInteger success = new AtomicInteger(0);
    for (int i = 0; i < times; i++) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    for (int j = 0; j < times; j++) {
                        final String ok_rest = restServiceRest.get("ok_rest");
                        Assert.assertEquals("serverok_rest", ok_rest);
                        success.incrementAndGet();
                    }
                } catch (Throwable e) {
                    e.printStackTrace();
                } finally {
                    latch.countDown();
                }
            }
        }).start();
    }
    latch.await();
    Assert.assertEquals(times * times, success.get());

    TimeUnit.SECONDS.sleep(5);

    List<String> clientDigestContents = memoryReporter.getClientDigestHolder();

    List<String> serverDigestContents = memoryReporter.getServerDigestHolder();

    List<JSONObject> clientDigest = TracerChecker.convertContents2Json(clientDigestContents);
    List<String> clientTraceIds = readTraceId(clientDigest);

    List<JSONObject> serverDigest = TracerChecker.convertContents2Json(serverDigestContents);

    List<String> serverTraceIds = readTraceId(serverDigest);

    Assert.assertTrue(CommonUtils.isNotEmpty(clientTraceIds));
    Assert.assertTrue(CommonUtils.isNotEmpty(serverTraceIds));

    HashSet<String> hashSet = new HashSet<String>(200);
    for (String clientTraceId : clientTraceIds) {
        //will not duplicate
        Assert.assertTrue(!hashSet.contains(clientTraceId));
        hashSet.add(clientTraceId);
        Assert.assertTrue(serverTraceIds.contains(clientTraceId));
    }

    //validate one rpc server and rpc client field

    boolean result = TracerChecker.validateTracerDigest(clientDigest.get(0), "client",
        RpcConstants.PROTOCOL_TYPE_REST);

    Assert.assertTrue(result);
    result = TracerChecker.validateTracerDigest(serverDigest.get(0), "server", RpcConstants.PROTOCOL_TYPE_REST);
    Assert.assertTrue(result);

}
 
Example 19
Source File: BoltConsumerBootstrapTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubscribe() throws Exception {
    RegistryConfig registryConfig = new RegistryConfig().setProtocol("mocktest");
    RegistryConfig registryConfig2 = new RegistryConfig().setProtocol("mocktestslow");

    ConsumerConfig<HelloService> consumerConfig3 = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setUniqueId("mock")
        .setRegistry(Arrays.asList(registryConfig, registryConfig2))
        .setTimeout(3000).setAddressWait(-1);
    long start = System.currentTimeMillis();
    consumerConfig3.refer();
    long end = System.currentTimeMillis();
    LOGGER.info("elapsed time " + (end - start) + "ms");
    Assert.assertTrue((end - start) > 2000 && (end - start) < 4000);
    Assert.assertTrue(consumerConfig3.getConsumerBootstrap().isSubscribed());
    Assert.assertTrue(consumerConfig3.getConsumerBootstrap().getCluster()
        .getAddressHolder().getAllProviderSize() == 0);

    // 发布一个服务,每个请求要执行2秒
    ServerConfig serverConfig0 = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22222)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);
    ProviderConfig<HelloService> providerConfig0 = new ProviderConfig<HelloService>()
        .setId("p-0")
        .setInterfaceId(HelloService.class.getName())
        .setUniqueId("mock")
        .setRef(new HelloServiceImpl(2000))
        .setServer(serverConfig0)
        .setRepeatedExportLimit(5)
        .setRegistry(registryConfig);
    providerConfig0.export();

    // 发布一个服务,每个请求要执行2秒
    ServerConfig serverConfig1 = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22223)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);
    ProviderConfig<HelloService> providerConfig1 = new ProviderConfig<HelloService>()
        .setId("p-1")
        .setInterfaceId(HelloService.class.getName())
        .setUniqueId("mock")
        .setRef(new HelloServiceImpl(2000))
        .setServer(serverConfig1)
        .setRepeatedExportLimit(5)
        .setRegistry(registryConfig2);
    providerConfig1.export();

    ConsumerConfig<HelloService> consumerConfig0 = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setUniqueId("mock")
        .setDirectUrl("bolt://127.0.0.1:22222")
        .setTimeout(3000);
    consumerConfig0.refer();
    Assert.assertTrue(consumerConfig0.getConsumerBootstrap().isSubscribed());
    consumerConfig0.refer();

    consumerConfig0.unRefer();
    consumerConfig0.unRefer();

    ConsumerConfig<HelloService> consumerConfig1 = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setUniqueId("mock")
        .setRegistry(Arrays.asList(registryConfig, registryConfig2))
        .setTimeout(3000).setAddressWait(-1);
    start = System.currentTimeMillis();
    consumerConfig1.refer();
    end = System.currentTimeMillis();
    LOGGER.info("elapsed time " + (end - start) + "ms");
    Assert.assertTrue((end - start) > 2000 && (end - start) < 4000);
    Assert.assertTrue(consumerConfig1.getConsumerBootstrap().isSubscribed());
    Assert.assertTrue(consumerConfig1.getConsumerBootstrap().getCluster()
        .getAddressHolder().getAllProviderSize() > 0);

    Assert.assertTrue(consumerConfig3.getConsumerBootstrap().getCluster()
        .getAddressHolder().getAllProviderSize() > 0);

    ConsumerConfig<HelloService> consumerConfig2 = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setUniqueId("mock")
        .setRegistry(Arrays.asList(registryConfig, registryConfig2))
        .setTimeout(3000).setAddressWait(1000);
    start = System.currentTimeMillis();
    consumerConfig2.refer();
    end = System.currentTimeMillis();
    LOGGER.info("elapsed time " + (end - start) + "ms");
    Assert.assertTrue((end - start) > 1000 && (end - start) < 3000);
    Assert.assertFalse(consumerConfig2.getConsumerBootstrap().isSubscribed());

    try {
        Thread.sleep(1500);
    } catch (Exception e) {
    }
    Assert.assertTrue(consumerConfig2.getConsumerBootstrap().getCluster()
        .getAddressHolder().getAllProviderSize() > 0);
}
 
Example 20
Source File: MultiProtocolServerExpTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultiProtocolExp() throws NoSuchFieldException {
    try {
        // 只有2个线程 执行
        ServerConfig serverConfig = new ServerConfig()
            .setStopTimeout(0)
            .setPort(22222)
            .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
            .setQueues(100).setCoreThreads(1).setMaxThreads(2);

        // 发布一个服务,每个请求要执行1秒
        ProviderConfig<RestService> providerConfig = new ProviderConfig<RestService>()
            .setInterfaceId(RestService.class.getName())
            .setRef(new RestServiceImpl())
            .setServer(serverConfig)
            .setRepeatedExportLimit(1)
            .setRegister(false);
        providerConfig.export();

        ServerConfig serverConfig2 = new ServerConfig()
            .setStopTimeout(0)
            .setPort(22223)
            .setProtocol(RpcConstants.PROTOCOL_TYPE_REST)
            .setQueues(100).setCoreThreads(1).setMaxThreads(2);

        // 发布一个服务,每个请求要执行1秒
        ProviderConfig<RestService> providerConfig2 = new ProviderConfig<RestService>()
            .setInterfaceId(RestService.class.getName())
            .setRef(new RestServiceImpl())
            .setServer(serverConfig2)
            .setRepeatedExportLimit(1)
            .setRegister(false);
        providerConfig2.export();

        ProviderConfig<RestService> providerConfig3 = new ProviderConfig<RestService>()
            .setInterfaceId(RestService.class.getName())
            .setRef(new RestServiceImpl())
            .setServer(serverConfig2)
            .setRepeatedExportLimit(1)
            .setRegister(false);
        providerConfig3.export();

        Assert.fail();
    } catch (Throwable e) {
        //reflect to fetch export key
        ConcurrentMap<String, AtomicInteger> map = null;

        Field field = DefaultProviderBootstrap.class.getDeclaredField("EXPORTED_KEYS");
        try {
            field.setAccessible(true);
            map = (ConcurrentMap<String, AtomicInteger>) field.get(null);
        } catch (IllegalAccessException e1) {
            e1.printStackTrace();
        }

        //two providers publish done, the third will false, and revert counter, export value is 1
        for (Map.Entry<String, AtomicInteger> entry : map.entrySet()) {
            AtomicInteger atomicInteger = entry.getValue();
            Assert.assertEquals(1, atomicInteger.get());
        }
    }
}