java 服务注册中心_springboot 注册服务注册中心(zk)的两种方式详解
时间: 2023-07-07 08:30:30 浏览: 50
在Spring Boot中,我们可以通过两种方式来注册服务到Zookeeper服务注册中心。
第一种方式是使用Zookeeper的原生API来注册服务,具体步骤如下:
1. 首先,我们需要引入Zookeeper客户端的依赖包,可以在pom.xml文件中添加如下依赖:
```xml
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.13</version>
</dependency>
```
2. 接下来,在Spring Boot的配置文件中,我们需要配置Zookeeper的连接信息,如下所示:
```yaml
spring:
zookeeper:
connect-string: localhost:2181
```
3. 然后,我们需要创建一个Zookeeper的客户端实例,并在应用启动时连接到Zookeeper服务注册中心:
```java
@Configuration
public class ZookeeperConfig {
@Value("${spring.zookeeper.connect-string}")
private String connectString;
@Bean
public ZooKeeper zooKeeper() throws IOException {
CountDownLatch countDownLatch = new CountDownLatch(1);
ZooKeeper zooKeeper = new ZooKeeper(connectString, 5000, event -> {
if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
countDownLatch.countDown();
}
});
countDownLatch.await();
return zooKeeper;
}
}
```
4. 最后,在需要注册服务的地方,我们可以调用Zookeeper客户端实例的create()方法来创建一个Zookeeper节点,并将服务信息保存在节点中:
```java
@Autowired
private ZooKeeper zooKeeper;
public void registerService(String serviceName, String serviceAddress) throws KeeperException, InterruptedException {
String servicePath = "/services/" + serviceName;
if (zooKeeper.exists(servicePath, false) == null) {
zooKeeper.create(servicePath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
}
String addressPath = servicePath + "/" + serviceAddress;
zooKeeper.create(addressPath, null, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
}
```
以上便是使用Zookeeper原生API注册服务的方式。
第二种方式是使用Spring Cloud Zookeeper提供的服务注册功能,具体步骤如下:
1. 首先,我们需要引入Spring Cloud Zookeeper的依赖包,可以在pom.xml文件中添加如下依赖:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
```
2. 接下来,在Spring Boot的配置文件中,我们需要配置Zookeeper的连接信息,如下所示:
```yaml
spring:
cloud:
zookeeper:
connect-string: localhost:2181
```
3. 最后,在需要注册服务的地方,我们可以使用Spring Cloud Zookeeper提供的@EnableDiscoveryClient注解来启用服务注册功能,并使用@Service注解将服务注册到Zookeeper服务注册中心:
```java
@SpringBootApplication
@EnableDiscoveryClient
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Service
public class DemoServiceImpl implements DemoService {
@Override
public String sayHello(String name) {
return "Hello, " + name + "!";
}
}
```
以上便是使用Spring Cloud Zookeeper注册服务的方式。