Dubbo 测试用例 获取注册中心的其他服务
package com.xyebank.uk.user.service; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.dubbo.config.ApplicationConfig; import com.alibaba.dubbo.config.ReferenceConfig; import com.alibaba.dubbo.config.RegistryConfig; import com.alibaba.fastjson.JSONObject; import com.xyebank.uk.bill.api.BillUserAmountService; import com.xyebank.uk.bill.api.vo.out.BalanceOutVo; import com.xyebank.uk.user.api.UserInfoService; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class DubboTests { //这种方式也可以取到注册中心的服务(区别在于,这种方式取到的服务,优先是本地服务,取不到才取 远程服务) @Autowired UserInfoService userInfoService; //这种方式也可以取到注册中心的服务 @Autowired BillUserAmountService billUserAmountService; @Test public void getService() throws Exception { ApplicationConfig applicationConfig = new ApplicationConfig(); applicationConfig.setName("test"); RegistryConfig registry = new RegistryConfig(); registry.setAddress("zookeeper://127.0.0.1:2181"); //通过这种方式可以获取注册中心的服务 ReferenceConfig<BillUserAmountService> reference = new ReferenceConfig<>(); reference.setApplication(applicationConfig); reference.setRegistry(registry); reference.setInterface(BillUserAmountService.class); reference.setVersion("1.0.0"); ReferenceConfig<UserInfoService> referenceUS = new ReferenceConfig<>(); referenceUS.setApplication(applicationConfig); referenceUS.setRegistry(registry); referenceUS.setInterface(UserInfoService.class); referenceUS.setVersion("1.0.0"); BillUserAmountService billUserAmountService2 = reference.get(); UserInfoService userInfoService2 = referenceUS.get(); System.out.println("取到的服务userInfoService:" + userInfoService ); System.out.println("取到的服务userInfoService2:" + userInfoService2 ); System.out.println("取到的服务billUserAmountService:" + billUserAmountService ); System.out.println("取到的服务billUserAmountService2:" + billUserAmountService2 ); System.out.println("取到的服务:" + JSONObject.toJSONString( userInfoService.queryById(444455694863835136L) ) ); System.out.println("取到的服务billUserAmountService:" + JSONObject.toJSONString( billUserAmountService.getBalance(444455694863835136L) ) ); System.out.println("取到的服务billUserAmountService2:" + JSONObject.toJSONString( billUserAmountService2.getBalance(444455694863835136L) ) ); } }
结果:可见 注入方式优先获取的 本地服务。通过 ReferenceConfig 只会获取到远程服务。
能耍的时候就一定要耍,不能耍的时候一定要学。
天道酬勤,贵在坚持
posted on 2022-04-12 17:49 zhangyukun 阅读(287) 评论(0) 编辑 收藏 举报