基于Curator实现dubbo服务自动注册发现
生活随笔
收集整理的這篇文章主要介紹了
基于Curator实现dubbo服务自动注册发现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 概念
- 基于ServiceDiscovery實現服務自動注冊和發現
- Service:服務基本信息
- InstanceDetails:封裝實例用過來保存到zk中
- ServiceProvider:服務提供者
- ServiceConsumer:服務消費者
- 運行
- 基于ServiceDiscovery、ServiceCache實現服務自動注冊和發現
- Registry:服務注冊Registry接口
- ZookeeperRegistry:基于zk 實現服務注冊發現
- ServerInfo:注冊信息
- ServiceProviderByCache:服務提供者
- ServiceComsumerByCache:服務發現者
概念
學習文章:https://blog.csdn.net/qq_34021712/article/details/82887942
基于ServiceDiscovery實現服務自動注冊和發現
Service:服務基本信息
package com.demo.rpc.curator;import java.util.List;/*** @author: weijie* @Date: 2020/9/27 16:32* @Description: Service:方法、方法描述、方法參數*/ public class Service {private String methodName;private String desc;private List<String> params;public String getMethodName() {return methodName;}public void setMethodName(String methodName) {this.methodName = methodName;}public String getDesc() {return desc;}public void setDesc(String desc) {this.desc = desc;}public List<String> getParams() {return params;}public void setParams(List<String> params) {this.params = params;} }InstanceDetails:封裝實例用過來保存到zk中
package com.demo.rpc.curator;import java.util.HashMap; import java.util.Map;public class InstanceDetails {//zk根節點路徑public static final String ROOT_PATH = "/service";//該服務擁有哪些方法public Map<String, Service> services = new HashMap<>();//服務描述private String serviceDesc;public InstanceDetails() {}public InstanceDetails(String serviceDesc, Map<String, Service> services) {this.services = services;this.serviceDesc = serviceDesc;}public static String getRootPath() {return ROOT_PATH;}public Map<String, Service> getServices() {return services;}public void setServices(Map<String, Service> services) {this.services = services;}public String getServiceDesc() {return serviceDesc;}public void setServiceDesc(String serviceDesc) {this.serviceDesc = serviceDesc;} }ServiceProvider:服務提供者
package com.demo.rpc.curator;import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.x.discovery.*; import org.apache.curator.x.discovery.details.JsonInstanceSerializer;import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.Map;public class ServiceProvider {public static void main(String[] args) throws Exception {CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181",2000,2000, new ExponentialBackoffRetry(1000, 3));client.start();client.blockUntilConnected();//服務構造器ServiceInstanceBuilder<InstanceDetails> serviceInstanceBuilder = ServiceInstance.builder();//該服務中所有接口Map<String, Service> services = new HashMap<>();Service addOrderService = new Service();addOrderService.setDesc("添加訂單");addOrderService.setMethodName("addOrder");addOrderService.setParams(Arrays.asList("uid", "createTime", "sid", "status"));services.put("addOrder", addOrderService);//添加刪除訂單服務接口Service delOrderService = new Service();delOrderService.setDesc("刪除訂單");delOrderService.setMethodName("delOrder");delOrderService.setParams(Arrays.asList("sid"));services.put("delOrder", delOrderService);InstanceDetails payload = new InstanceDetails("訂單服務", services);//將服務添加到ServiceInstanceServiceInstance<InstanceDetails> orderService = serviceInstanceBuilder.address("127.0.0.1").port(8080).name("OrderService").payload(payload).uriSpec(new UriSpec("{scheme}://{address}:{port}")).build();//構建ServiceDiscovery用來做服務發現ServiceDiscovery<InstanceDetails> serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).serializer(new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class)).basePath(InstanceDetails.ROOT_PATH).build();//服務注冊serviceDiscovery.registerService(orderService);serviceDiscovery.start();System.out.println("服務注冊成功");//創建鉤子方法正常關閉Runtime.getRuntime().addShutdownHook(new Thread(() -> {try {serviceDiscovery.close();client.close();} catch (IOException e) {e.printStackTrace();}System.out.println("shutdown hook...");}));//保持服務運行狀態ServiceProvider serviceProvider = new ServiceProvider();synchronized (serviceProvider){serviceProvider.wait();}}}ServiceConsumer:服務消費者
package com.demo.rpc.curator;import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.details.JsonInstanceSerializer;import java.util.Collection; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit;public class ServiceConsumer {public static void main(String[] args) throws Exception {CuratorFramework client = CuratorFrameworkFactory.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));client.start();client.blockUntilConnected();//構建ServiceDiscovery用來做服務發現ServiceDiscovery<InstanceDetails> serviceDiscovery = ServiceDiscoveryBuilder.builder(InstanceDetails.class).client(client).basePath(InstanceDetails.ROOT_PATH).serializer(new JsonInstanceSerializer<InstanceDetails>(InstanceDetails.class)).build();serviceDiscovery.start();//模擬請求調用服務while (true) {Collection<ServiceInstance<InstanceDetails>> orderServices = serviceDiscovery.queryForInstances("OrderService");if (orderServices.size() == 0) {System.out.println("當前沒有發現服務");TimeUnit.SECONDS.sleep(10);continue;}for (ServiceInstance<InstanceDetails> service : orderServices) {//獲取請求的scheme 例如:http://127.0.0.1:8080String uriSpec = service.buildUriSpec();//獲取服務的其他信息InstanceDetails payload = service.getPayload();//服務描述String serviceDesc = payload.getServiceDesc();//獲取該服務下的所有接口Map<String, Service> allService = payload.getServices();Set<Map.Entry<String, Service>> entries = allService.entrySet();for (Map.Entry<String, Service> entry : entries) {System.out.println(serviceDesc + uriSpec+ "/" + service.getName()+ "/" + entry.getKey()+ " 該方法需要的參數為:"+ entry.getValue().getParams().toString());}}System.out.println("---------------------");Thread.sleep(5 * 1000);}}}運行
基于ServiceDiscovery、ServiceCache實現服務自動注冊和發現
Registry:服務注冊Registry接口
package com.demo.rpc.curator;import org.apache.curator.x.discovery.ServiceInstance;import java.util.List;public interface Registry<T> {void registerService(ServiceInstance<T> service) throws Exception;void unRegisterService(ServiceInstance<T> service) throws Exception;List<ServiceInstance<T>> queryForInstances(String name) throws Exception;}ZookeeperRegistry:基于zk 實現服務注冊發現
package com.demo.rpc.curator;import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.retry.ExponentialBackoffRetry; import org.apache.curator.x.discovery.ServiceCache; import org.apache.curator.x.discovery.ServiceDiscovery; import org.apache.curator.x.discovery.ServiceDiscoveryBuilder; import org.apache.curator.x.discovery.ServiceInstance; import org.apache.curator.x.discovery.details.InstanceSerializer; import org.apache.curator.x.discovery.details.JsonInstanceSerializer;import java.util.List; import java.util.stream.Collectors;public class ZookeeperRegistry<T> implements Registry{private InstanceSerializer serializer = new JsonInstanceSerializer(ServerInfo.class);private ServiceDiscovery<T> serviceDiscovery;private ServiceCache<T> serviceCache;private String ROOT = "/dubbo-demo";private String serviceName = "demoService";private String host;public ZookeeperRegistry(String host) {this.host = host;}public void start() throws Exception{CuratorFramework client = CuratorFrameworkFactory.newClient(this.host, new ExponentialBackoffRetry(1000, 5));client.start();serviceDiscovery = ServiceDiscoveryBuilder.builder(ServerInfo.class).client(client).basePath(ROOT).serializer(serializer).build();serviceDiscovery.start();//監聽zk節點信息變化,方便后續的讀取serviceCache = serviceDiscovery.serviceCacheBuilder()//多個serviceName如何監聽??.name(serviceName).build();serviceDiscovery.start();serviceCache.start();}@Overridepublic void registerService(ServiceInstance service) throws Exception {serviceDiscovery.registerService(service);}@Overridepublic void unRegisterService(ServiceInstance service) throws Exception {serviceDiscovery.unregisterService(service);}/*** @param name* @return 根據name查詢緩存數據* @throws Exception*/@Overridepublic List<ServiceInstance> queryForInstances(String name) throws Exception {return serviceCache.getInstances().stream().filter(s -> s.getName().equals(name)).collect(Collectors.toList());} }ServerInfo:注冊信息
package com.demo.rpc.curator;import java.io.Serializable;public class ServerInfo implements Serializable {private String host;private int port;public ServerInfo() {}public ServerInfo(String host, int port) {this.host = host;this.port = port;}public String getHost() {return host;}public void setHost(String host) {this.host = host;}public int getPort() {return port;}public void setPort(int port) {this.port = port;}@Overridepublic String toString() {return "ServerInfo{" +"host='" + host + '\'' +", port=" + port +'}';} }ServiceProviderByCache:服務提供者
package com.demo.rpc.curator;import org.apache.curator.x.discovery.ServiceInstance;public class ServiceProviderByCache {public static void main(String[] args) throws Exception {ZookeeperRegistry<ServerInfo> zookeeperRegistry = new ZookeeperRegistry<>("127.0.0.1:2181");zookeeperRegistry.start();ServerInfo serverInfo = new ServerInfo("127.0.0.1", 8080);zookeeperRegistry.registerService(ServiceInstance.builder().name("demoService").payload(serverInfo).build());synchronized (ServiceProviderByCache.class){ServiceProviderByCache.class.wait();}}}ServiceComsumerByCache:服務發現者
package com.demo.rpc.curator;import org.apache.curator.x.discovery.ServiceInstance;import java.util.List;public class ServiceComsumerByCache {public static void main(String[] args) throws Exception {ZookeeperRegistry<ServerInfo> zookeeperRegistry = new ZookeeperRegistry<>("127.0.0.1:2181");zookeeperRegistry.start();// while (true){List<ServiceInstance> serviceInstances = zookeeperRegistry.queryForInstances("demoService");for (ServiceInstance serviceInstance : serviceInstances){System.out.println(serviceInstance.getPayload().toString());} // }}}總結
以上是生活随笔為你收集整理的基于Curator实现dubbo服务自动注册发现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: yum安装rz、
- 下一篇: 【转载保存】ExecutorServic