Java Code Examples for com.alipay.sofa.rpc.config.ConsumerConfig#refer()

The following examples show how to use com.alipay.sofa.rpc.config.ConsumerConfig#refer() . 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: ServerB.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {

        // B服务里的C服务客户端
        ConsumerConfig<ServiceC> consumerConfig = new ConsumerConfig<ServiceC>()
            .setApplication(new ApplicationConfig().setAppName("BBB"))
            .setInterfaceId(ServiceC.class.getName())
            .setDirectUrl("bolt://127.0.0.1:12299?appName=CCC")
            .setRegister(false)
            .setInvokeType("callback") // 不设置,调用级别可设置
            .setTimeout(2000);

        ServiceC serviceC = consumerConfig.refer();

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

        ProviderConfig<ServiceB> providerConfig = new ProviderConfig<ServiceB>()
            .setInterfaceId(ServiceB.class.getName())
            .setApplication(new ApplicationConfig().setAppName("BBB"))
            .setRef(new ServiceBImpl(serviceC))
            .setServer(serverConfig)
            .setRegister(false);

        providerConfig.export();
    }
 
Example 2
Source File: LazyConnectTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testLazyFail() {

    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setDirectUrl("bolt://127.0.0.1:22223")
        .setTimeout(1000)
        .setLazy(true)
        .setRepeatedReferLimit(-1)
        .setRegister(false);
    final HelloService helloService = consumerConfig.refer();

    int count1 = 0;
    for (int i = 0; i < 4; i++) {
        try {
            helloService.sayHello("xxx", 20 + i);
            count1++;
        } catch (Exception ignore) {
        }
    }
    Assert.assertEquals(count1, 0);
}
 
Example 3
Source File: AllConnectConnectionHolderTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void getAvailableClientTransport1() throws Exception {
    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setDirectUrl("bolt://127.0.0.1:22221")
        .setConnectionHolder("all")
        .setRegister(false)
        .setLazy(true)
        .setTimeout(3000);
    HelloService helloService = consumerConfig.refer();
    ClientProxyInvoker invoker = (ClientProxyInvoker) ProxyFactory.getInvoker(helloService,
        consumerConfig.getProxy());
    Cluster cluster = invoker.getCluster();
    Assert.assertTrue(cluster.getConnectionHolder() instanceof AllConnectConnectionHolder);
    AllConnectConnectionHolder holder = (AllConnectConnectionHolder) cluster.getConnectionHolder();

    Assert.assertTrue(holder.isAvailableEmpty());
    Assert.assertNull(holder.getAvailableClientTransport(
        ProviderHelper.toProviderInfo("bolt://127.0.0.1:22221?serialization=hessian2")));

}
 
Example 4
Source File: AllConnectConnectionHolderTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void getAvailableClientTransport2() throws Exception {
    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setDirectUrl("bolt://127.0.0.1:22223,bolt://127.0.0.1:22224")
        .setConnectionHolder("all")
        .setRegister(false)
        .setLazy(true)
        .setTimeout(3000);
    HelloService helloService = consumerConfig.refer();
    ClientProxyInvoker invoker = (ClientProxyInvoker) ProxyFactory.getInvoker(helloService,
        consumerConfig.getProxy());
    Cluster cluster = invoker.getCluster();
    Assert.assertTrue(cluster.getConnectionHolder() instanceof AllConnectConnectionHolder);
    AllConnectConnectionHolder holder = (AllConnectConnectionHolder) cluster.getConnectionHolder();

    Assert.assertTrue(holder.isAvailableEmpty());
    Assert.assertNotNull(holder.getAvailableClientTransport(
        ProviderHelper.toProviderInfo("bolt://127.0.0.1:22223")));
    Assert.assertNotNull(holder.getAvailableClientTransport(
        ProviderHelper.toProviderInfo("bolt://127.0.0.1:22224")));
    consumerConfig.unRefer();
}
 
Example 5
Source File: BoltMockTest.java    From sofa-rpc with Apache License 2.0 6 votes vote down vote up
@Test
public void testRemote() {

    HttpMockServer.initSever(1235);
    HttpMockServer.addMockPath("/", JSON.toJSONString("mockJson"));
    HttpMockServer.start();
    final ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setBootstrap("bolt")
        .setApplication(new ApplicationConfig().setAppName("clientApp"))
        .setReconnectPeriod(1000)
        .setMockMode(MockMode.REMOTE)
        .setParameter("mockUrl", "http://127.0.0.1:1235/");

    HelloService helloService = consumerConfig.refer();
    Assert.assertEquals("mockJson", helloService.sayHello("xx", 22));

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

        ApplicationConfig applicationConfig = new ApplicationConfig().setAppName("oneway-client");

        ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
            .setApplication(applicationConfig)
            .setInterfaceId(HelloService.class.getName())
            .setInvokeType(RpcConstants.INVOKER_TYPE_ONEWAY)
            .setTimeout(50000)
            .setDirectUrl("bolt://127.0.0.1:22222?appName=oneway-server");
        HelloService helloService = consumerConfig.refer();

        ConsumerConfig<EchoService> consumerConfig2 = new ConsumerConfig<EchoService>()
            .setApplication(applicationConfig)
            .setInterfaceId(EchoService.class.getName())
            .setInvokeType(RpcConstants.INVOKER_TYPE_ONEWAY)
            .setTimeout(50000)
            .setDirectUrl("bolt://127.0.0.1:22222?appName=oneway-server");
        EchoService echoService = consumerConfig2.refer();

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

        while (true) {
            try {
                String s1 = helloService.sayHello("xxx", 22);
                LOGGER.warn("must null :{}", s1);

                String s2 = echoService.echoStr("yyy");
                LOGGER.warn("must null :{}", s2);

            } catch (Exception e) {
                LOGGER.error(e.getMessage(), e);
            }
            try {
                Thread.sleep(2000);
            } catch (Exception ignore) {
            }
        }

    }
 
Example 7
Source File: ZookeeperAuthBoltServerTest.java    From sofa-rpc with Apache License 2.0 5 votes vote down vote up
@Test
public void testUseCorrentAuth() {

    parameters.put("scheme", "digest");
    //如果存在多个认证信息,则在参数形式为为user1:passwd1,user2:passwd2
    parameters.put("addAuth", "sofazk:rpc1");

    registryConfig = new RegistryConfig()
        .setProtocol(RpcConstants.REGISTRY_PROTOCOL_ZK)
        .setAddress("127.0.0.1:2181/authtest")
        .setParameters(parameters);

    serverConfig = new ServerConfig()
        .setProtocol("bolt") // 设置一个协议,默认bolt
        .setPort(12200) // 设置一个端口,默认12200
        .setDaemon(false); // 非守护线程

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

    ConsumerConfig<EchoService> consumerConfig = new ConsumerConfig<EchoService>()
        .setRegistry(registryConfig)
        .setInterfaceId(EchoService.class.getName()) // 指定接口
        .setProtocol("bolt") // 指定协议
        .setTimeout(3000)
        .setConnectTimeout(10 * 1000);
    EchoService echoService = consumerConfig.refer();

    String result = echoService.echoStr("auth test");

    Assert.assertEquals("auth test", result);

}
 
Example 8
Source File: BoltDirectUrlTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
public void testAll() {
    // 只有2个线程 执行
    ServerConfig serverConfig = new ServerConfig()
        .setPort(12300)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setDaemon(true);

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

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

    HelloService helloService = consumerConfig.refer();

    Assert.assertNotNull(helloService.sayHello("xx", 22));

    serverConfig.getServer().stop();

    // 关闭后再调用一个抛异常
    try {
        helloService.sayHello("xx", 22);
    } 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.assertNotNull(helloService.sayHello("xx", 22));
}
 
Example 9
Source File: RejectedTest.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(0).setCoreThreads(1).setMaxThreads(2);

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

    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setTimeout(3000)
        .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 = 3;
    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) {
                    if (e instanceof SofaRpcException) {
                        Assert.assertEquals(((SofaRpcException) e).getErrorType(), RpcErrorType.SERVER_BUSY);
                    }
                    failure.incrementAndGet();
                } finally {
                    latch.countDown();
                }
            }
        }, "T1");
        thread1.start();
    }

    try {
        latch.await(10000, TimeUnit.MILLISECONDS);
    } catch (InterruptedException ignore) {
    }
    Assert.assertEquals(success.get(), 2);
    Assert.assertEquals(failure.get(), 1);

}
 
Example 10
Source File: FailoverClusterTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testMultiServer() {

    // 发布一个服务,每个请求要执行2秒
    ServerConfig serverConfig = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22223)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);
    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl(2000))
        .setServer(serverConfig)
        .setRepeatedExportLimit(-1)
        .setRegister(false);
    providerConfig.export();

    // 再发布一个服务,不等待
    ServerConfig serverConfig2 = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22224)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);
    ProviderConfig<HelloService> providerConfig2 = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl())
        .setServer(serverConfig2)
        .setRepeatedExportLimit(-1)
        .setRegister(false);
    providerConfig2.export();

    ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setDirectUrl("bolt://127.0.0.1:22223;bolt://127.0.0.1:22224")
        .setTimeout(1000)
        .setCluster("failover")
        .setRetries(1) // 失败后重试一次
        .setRegister(false);
    final HelloService helloService = consumerConfig.refer();

    int count2 = 0;
    for (int i = 0; i < 4; i++) {
        try {
            helloService.sayHello("xxx", 22);
            count2++;
        } catch (Exception ignore) {
            ignore.printStackTrace();
        }
    }
    Assert.assertEquals(4, count2);
}
 
Example 11
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 12
Source File: CustomizeFilterTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@BeforeClass
public static void beforeClass() {
    customizeContainerRequestTestFilter = new CustomizeContainerRequestTestFilter();
    customizeContainerResponseTestFilter = new CustomizeContainerResponseTestFilter();
    customizeClientRequestTestFilter = new CustomizeClientRequestTestFilter();
    customizeClientResponseTestFilter = new CustomizeClientResponseTestFilter();

    JAXRSProviderManager.registerCustomProviderInstance(customizeContainerRequestTestFilter);
    JAXRSProviderManager.registerCustomProviderInstance(customizeContainerResponseTestFilter);
    JAXRSProviderManager.registerCustomProviderInstance(customizeClientRequestTestFilter);
    JAXRSProviderManager.registerCustomProviderInstance(customizeClientResponseTestFilter);

    providerFilter = new CustomizeTestFilter();
    List<Filter> providerFilters = new ArrayList<Filter>(2);
    providerFilters.add(providerFilter);

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

    List<ServerConfig> servers = new ArrayList<ServerConfig>(2);
    servers.add(restServer);
    providerConfig = new ProviderConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setRef(new RestServiceImpl())
        .setRegister(false)
        .setServer(servers)
        .setFilterRef(providerFilters);

    providerConfig.export();

    //rest服务
    clientFilter = new CustomizeTestFilter();
    List<Filter> clientFilters = new ArrayList<Filter>(2);
    clientFilters.add(clientFilter);

    ConsumerConfig<RestService> consumerConfigRest = new ConsumerConfig<RestService>()
        .setInterfaceId(RestService.class.getName())
        .setProtocol(RpcConstants.PROTOCOL_TYPE_REST)
        .setDirectUrl("rest://127.0.0.1:8583")
        .setTimeout(1000)
        .setFilterRef(clientFilters)
        .setApplication(new ApplicationConfig().setAppName("TestClientRest"));
    filterRestService = consumerConfigRest.refer();
}
 
Example 13
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 14
Source File: ReconnectTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testReconnect() throws Exception {
    ServerConfig serverConfig1 = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22221)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);
    ProviderConfig<HelloService> providerConfig = new ProviderConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl())
        .setServer(serverConfig1)
        .setRepeatedExportLimit(-1)
        .setRegister(false);
    providerConfig.export();

    final ConsumerConfig<HelloService> consumerConfig = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setDirectUrl("bolt://127.0.0.1:22221")
        .setConnectionHolder("all")
        .setRegister(false)
        .setLazy(true)
        .setReconnectPeriod(2000)
        .setTimeout(3000);
    HelloService helloService = consumerConfig.refer();
    Assert.assertNotNull(helloService.sayHello("xxx", 11));

    // Mock server down, and RPC will throw exception(no available provider)
    providerConfig.unExport();
    ServerFactory.destroyAll();

    BoltClientTransport clientTransport = (BoltClientTransport) consumerConfig.getConsumerBootstrap().getCluster()
        .getConnectionHolder()
        .getAvailableClientTransport(ProviderHelper.toProviderInfo("bolt://127.0.0.1:22221"));

    clientTransport.disconnect();

    TestUtils.delayGet(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return consumerConfig.getConsumerBootstrap().getCluster().getConnectionHolder().isAvailableEmpty();
        }
    }, true, 100, 30);

    try {
        helloService.sayHello("xxx", 11);
        Assert.fail();
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains(LogCodes.ERROR_TARGET_URL_INVALID));
    }

    // Mock server restart
    serverConfig1 = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22221)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);
    providerConfig.setServer(Arrays.asList(serverConfig1)).export();
    // The consumer will reconnect to provider automatically
    TestUtils.delayGet(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            return consumerConfig.getConsumerBootstrap().getCluster().getConnectionHolder().isAvailableEmpty();
        }
    }, false, 100, 30);
    // RPC return success
    Assert.assertNotNull(helloService.sayHello("xxx", 11));
}
 
Example 15
Source File: TripleServerTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
//同步调用,直连
public void testSyncTimeout() {

    ApplicationConfig applicationConfig = new ApplicationConfig().setAppName("triple-server");

    int port = 50052;

    ServerConfig serverConfig = new ServerConfig()
        .setProtocol(RpcConstants.PROTOCOL_TYPE_TRIPLE)
        .setPort(port);

    ProviderConfig<SofaGreeterTriple.IGreeter> providerConfig = new ProviderConfig<SofaGreeterTriple.IGreeter>()
        .setApplication(applicationConfig)
        .setBootstrap(RpcConstants.PROTOCOL_TYPE_TRIPLE)
        .setInterfaceId(SofaGreeterTriple.IGreeter.class.getName())
        .setRef(new GreeterImpl())
        .setServer(serverConfig);

    providerConfig.export();

    ConsumerConfig<SofaGreeterTriple.IGreeter> consumerConfig = new ConsumerConfig<SofaGreeterTriple.IGreeter>();
    consumerConfig.setInterfaceId(SofaGreeterTriple.IGreeter.class.getName())
        .setProtocol(RpcConstants.PROTOCOL_TYPE_TRIPLE)
        .setDirectUrl("tri://127.0.0.1:" + port)
        .setTimeout(1);

    SofaGreeterTriple.IGreeter greeterBlockingStub = consumerConfig.refer();

    HelloRequest.DateTime dateTime = HelloRequest.DateTime.newBuilder().setDate("2018-12-28").setTime("11:13:00")
        .build();
    HelloReply reply = null;
    HelloRequest request = HelloRequest.newBuilder().setName("world").setDateTime(dateTime).build();

    boolean exp = false;
    try {
        reply = greeterBlockingStub.sayHello(request);
    } catch (SofaTimeOutException e) {
        exp = true;
    }
    Assert.assertTrue(exp);

}
 
Example 16
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 17
Source File: BaggageSyncTest.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.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.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.setTimeout(3000);

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

    // 开始测试
    RpcInvokeContext context = RpcInvokeContext.getContext();
    context.putRequestBaggage("reqBaggageB", "a2bbb");
    context.putRequestBaggage("reqBaggageC", "a2ccc");
    context.putRequestBaggage("reqBaggageD", "a2ddd");
    String ret = service.hello();
    Assert.assertEquals(ret, "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.hello();
    Assert.assertEquals(ret, "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 18
Source File: TripleHessianInvokeTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testInvoke() throws InterruptedException {
    RpcRunningState.setDebugMode(true);

    ApplicationConfig clientApp = new ApplicationConfig().setAppName("triple-client");

    ApplicationConfig serverApp = new ApplicationConfig().setAppName("triple-server");

    int port = 50062;

    ServerConfig serverConfig = new ServerConfig()
        .setProtocol(RpcConstants.PROTOCOL_TYPE_TRIPLE)
        .setPort(port);

    TripleHessianInterfaceImpl ref = new TripleHessianInterfaceImpl();
    ProviderConfig<TripleHessianInterface> providerConfig = new ProviderConfig<TripleHessianInterface>()
        .setApplication(serverApp)
        .setBootstrap(RpcConstants.PROTOCOL_TYPE_TRIPLE)
        .setInterfaceId(TripleHessianInterface.class.getName())
        .setRef(ref)
        .setServer(serverConfig)
        .setRegister(false);

    providerConfig.export();

    ConsumerConfig<TripleHessianInterface> consumerConfig = new ConsumerConfig<TripleHessianInterface>();
    consumerConfig.setInterfaceId(TripleHessianInterface.class.getName())
        .setProtocol(RpcConstants.PROTOCOL_TYPE_TRIPLE)
        .setDirectUrl("localhost:" + port)
        .setRegister(false)
        .setApplication(clientApp);

    TripleHessianInterface helloService = consumerConfig.refer();

    Thread.sleep(10 * 1000);
    LOGGER.info("Grpc stub bean successful: {}", helloService.getClass().getName());
    helloService.call();
    Assert.assertEquals("call", ref.getFlag());

    String s = helloService.call1();
    Assert.assertEquals("call1", ref.getFlag());
    Assert.assertEquals("call1", s);

    Request request = new Request();
    int age = RandomUtils.nextInt();
    request.setAge(age);
    String call2 = "call2";
    request.setFlag(call2);
    Response response = helloService.call2(request);
    Assert.assertEquals(age, response.getAge());
    Assert.assertEquals(call2, response.getFlag());

    Response response1 = helloService.call2(null);
    Assert.assertNull(response1);

}
 
Example 19
Source File: GenericClientMain.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("generic-client");

    ConsumerConfig<GenericService> consumerConfig = new ConsumerConfig<GenericService>()
        .setApplication(applicationConfig)
        .setInterfaceId(TestGenericService.class.getName())
        .setGeneric(true)
        .setTimeout(50000)
        .setDirectUrl("bolt://127.0.0.1:22222?appName=generic-server");
    GenericService testService = consumerConfig.refer();

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

    while (true) {
        try {
            String s1 = (String) testService.$invoke("echoStr", new String[] { "java.lang.String" },
                new Object[] { "1111" });
            LOGGER.warn("generic return :{}", s1);

            GenericObject genericObject = new GenericObject(
                "com.alipay.sofa.rpc.invoke.generic.TestObj");
            genericObject.putField("str", "xxxx");
            genericObject.putField("num", 222);

            GenericObject o2 = (GenericObject) testService.$genericInvoke("echoObj",
                new String[] { "com.alipay.sofa.rpc.invoke.generic.TestObj" },
                new Object[] { genericObject });
            LOGGER.warn("generic return :{}", o2);

            TestObj o3 = testService.$genericInvoke("echoObj",
                new String[] { "com.alipay.sofa.rpc.invoke.generic.TestObj" },
                new Object[] { genericObject }, TestObj.class);
            LOGGER.warn("generic return :{}", o3);

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        try {
            Thread.sleep(2000);
        } catch (Exception ignore) {
        }
    }

}
 
Example 20
Source File: BoltProviderBootstrapTest.java    From sofa-rpc with Apache License 2.0 4 votes vote down vote up
@Test
public void testProviderClassLoader() throws Throwable {
    // 发布一个服务
    ServerConfig serverConfig = new ServerConfig()
        .setStopTimeout(0)
        .setPort(22223)
        .setProtocol(RpcConstants.PROTOCOL_TYPE_BOLT)
        .setQueues(100).setCoreThreads(5).setMaxThreads(5);
    ProviderConfig<HelloService> providerConfig0 = new ProviderConfig<HelloService>()
        .setId("p-0")
        .setUniqueId("p-0")
        .setInterfaceId(HelloService.class.getName())
        .setRef(new HelloServiceImpl())
        .setServer(serverConfig)
        .setRegister(false);
    providerConfig0.export();

    // incompatible with JDK 9+
    URLClassLoader currentClassLoader = (URLClassLoader) this.getClass().getClassLoader();
    TempClassLoader tempClassLoader = new TempClassLoader(currentClassLoader.getURLs(), null);
    Class helloService = tempClassLoader.loadClass(HelloService.class.getCanonicalName());
    Class helloServiceImpl = tempClassLoader.loadClass(HelloServiceImpl.class.getCanonicalName());

    ProviderConfig<Object> providerConfig1 = new ProviderConfig<Object>()
        .setId("p-1")
        .setUniqueId("p-1")
        .setInterfaceId(HelloService.class.getName())
        .setProxyClass(helloService)
        .setRef(helloServiceImpl.getConstructor(int.class).newInstance(2000))
        .setServer(serverConfig)
        .setRegister(false);
    providerConfig1.export();

    // refer a service
    ConsumerConfig<HelloService> consumerConfig0 = new ConsumerConfig<HelloService>()
        .setInterfaceId(HelloService.class.getName())
        .setUniqueId("p-0")
        .setProxy("jdk")
        .setDirectUrl("bolt://127.0.0.1:22223")
        .setTimeout(500);
    HelloService proxy = consumerConfig0.refer();
    proxy.sayHello("11", 11);

    ClassLoader cl0 = ReflectCache.getServiceClassLoader(ConfigUniqueNameGenerator.getUniqueName(providerConfig0));
    ClassLoader cl1 = ReflectCache.getServiceClassLoader(ConfigUniqueNameGenerator.getUniqueName(providerConfig1));

    Assert.assertEquals(currentClassLoader, cl0);
    Assert.assertEquals(tempClassLoader, cl1);

    providerConfig0.unExport();
    providerConfig1.unExport();
    cl0 = ReflectCache.getServiceClassLoader(ConfigUniqueNameGenerator.getUniqueName(providerConfig0));
    cl1 = ReflectCache.getServiceClassLoader(ConfigUniqueNameGenerator.getUniqueName(providerConfig1));
    Assert.assertEquals(ClassLoaderUtils.getCurrentClassLoader(), cl0);
    Assert.assertEquals(ClassLoaderUtils.getCurrentClassLoader(), cl1);

    Method methodCache = ReflectCache.getMethodCache(ConfigUniqueNameGenerator.getUniqueName(providerConfig0),
        "sayHello");
    Assert.assertNull(methodCache);

    methodCache = ReflectCache.getOverloadMethodCache(ConfigUniqueNameGenerator.getUniqueName(providerConfig0),
        "sayHello", new String[] { "java.lang.Stringint" });
    Assert.assertNull(methodCache);

    String[] sig = ReflectCache.getMethodSigsCache(ConfigUniqueNameGenerator.getUniqueName(providerConfig0),
        "sayHello");
    Assert.assertNull(sig);
}