当前位置:网站首页>curator - 实现服务注册与发现
curator - 实现服务注册与发现
2022-06-09 11:27:00 【iiaythi】
curator 实现服务注册与发现
AppInstance 实例
@AllArgsConstructor
@Data
public class AppInstance {
private String address;
private int port;
}
ServerRegistar 服务注册和发现
@Component
public class ServerRegistar {
@Autowired
private CuratorFramework client;
private Map<String, List<AppInstance>> services = new HashMap<>();
@Value(value = "${spring.application.name}")
private String service;
public void register(String address, int port) {
try {
String path = "/services/" + service + "/" + address + ":" + port;
client.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath(path);
System.out.println("服务注册成功,路径为:" + path);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void discover() {
CuratorCache cache = CuratorCache.builder(client, "/services").build();
CuratorCacheListener listener = CuratorCacheListener.builder()
.forTreeCache(client, new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
TreeCacheEvent.Type type = event.getType();
if (event.getData()==null){
return;
}
String path = event.getData().getPath();
System.out.println("事件类型:" + type + ",路径:" + path);
if (StrUtil.isEmpty(path)) {
return;
}
String[] paths = path.split("/");
if (paths.length <= 3){
return;
}
// /services/serviceName/ip:port
if (type == TreeCacheEvent.Type.NODE_ADDED) {
System.out.println("服务发现:" + event.getData().getPath());
String serviceName = paths[2];
String address = paths[3].split(":")[0];
int port = Integer.parseInt(paths[3].split(":")[1]);
AppInstance appInstance = new AppInstance(address, port);
services.computeIfAbsent(serviceName, k -> {
List<AppInstance> appInstances = new ArrayList<>();
return appInstances;
}).add(appInstance);
}else if(type == TreeCacheEvent.Type.NODE_REMOVED){
System.out.println("服务移除:" + event.getData().getPath());
String serviceName = paths[2];
String address = paths[3].split(":")[0];
int port = Integer.parseInt(paths[3].split(":")[1]);
AppInstance appInstance = new AppInstance(address, port);
services.computeIfAbsent(serviceName, k -> {
List<AppInstance> appInstances = new ArrayList<>();
return appInstances;
}).remove(appInstance);
}
}
}).build();
cache.listenable().addListener(listener);
cache.start();
}
public Map<String, List<AppInstance>> getServices() {
return services;
}
}
SeviceRegistrListener 启动监听
在 spring boot 应用启动的时候 去进行服务注册 和 服务发现
@Component
public class SeviceRegistrListener implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private ServerRegistar serverRegistar;
@Value(value = "${server.port}")
private int port;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
String hostAddress = NetUtil.getLocalhost().getHostAddress();
serverRegistar.register(hostAddress, port);
//发现
serverRegistar.discover();
}
}
ServiceDiscoveryController 服务暴露
@RestController
public class ServiceDiscoveryController {
@Autowired
private ServerRegistar serverRegistar;
@GetMapping("/services")
public Map<String, List<AppInstance>> index() {
return serverRegistar.getServices();
}
}
服务启动
事件类型:NODE_ADDED,路径:/services/boot-curator/172.23.0.1:8081
服务发现:/services/boot-curator/172.23.0.1:8081
事件类型:NODE_REMOVED,路径:/services/boot-curator/172.23.0.1:8081
服务移除:/services/boot-curator/172.23.0.1:8081
事件类型:NODE_ADDED,路径:/services/boot-product
事件类型:NODE_ADDED,路径:/services/boot-product/172.23.0.1:8081
服务发现:/services/boot-product/172.23.0.1:8081
事件类型:NODE_REMOVED,路径:/services/boot-product/172.23.0.1:8081
服务移除:/services/boot-product/172.23.0.1:8081
http://localhost:8080/services:
{
"boot-product": [
{
"address": "172.23.0.1",
"port": 8081
}
],
"boot-curator": [
{
"address": "172.23.0.1",
"port": 8080
}
]
}
边栏推荐
- [untitled]
- 清空表格选中项clearSelection
- 07 | the second step of the mid platform landing: enterprise digital panoramic planning (define)
- H3C Certified Wireless Internet expert
- Redis数据结构与介绍
- 利用放射get 实体对象属性 记录
- 你的微服务敢独立交付么?
- Preparation guide for the 2022 soft exam network engineer exam
- 01 | 来龙去脉:中台为什么这么火?
- [reprint] understand G1 garbage collector
猜你喜欢

04 | 万事预则立:中台建设前必须想清楚的四个问题

7.移除元素

Prompt credssp encryption database correction when windows is remote

07 | 中台落地第二步:企业数字化全景规划(Define)

Security evaluation of commercial password application

LR11安装报错:此计算机上缺少vc2005_sp1_with_atl_fix_redist,请安装所有缺少的必要组件,然后重新运行此安装。

Origin:无法导入数据,粘贴数据卡死的解决办法

8.搜索插入位置

Win10 your organization has turned off automatic update. How to solve the problem?

Several ways of traversing map
随机推荐
[reprint] what is the "brain crack" of distributed systems?
LeetCode相机最小问题
07 | 中台落地第二步:企业数字化全景规划(Define)
H3C certified cloud computing Engineer
Anonymous inner classes and local variables
Preparation guide for 2022 soft test information security engineer examination
6. exchange the nodes in the linked list in pairs
dotnet core 也能协调分布式事务啦!
H3C certified route switching Internet expert
How much bandwidth is required to view 1080p, 2k and 4K videos smoothly?
Journal of the Chinese Academy of Sciences Bao Yungang: to accelerate the development of key core technologies, we must grasp the laws of Technological Development
Calculate the result of a string formula
给 Web3 项目的智能合约安全指南
Gson, fastjason, Jackson serialization differences
3dmax如何建模(一)
go-zero 微服务实战系列(二、服务拆分)
H3C Certified Safety Technology Senior Engineer
Gson、FastJson、Jackson 序列化区别
Iphone5s display disabled solution
How to solve the existing 1px problem?