之前采用的注册中心是eureka,现在换成zookeeper,我们重新创建一个模块来演示,嗯,来吧。
1.创建支付模块8004
2.引入依赖
<dependencies> <dependency> <groupId>cn.aib.springcloud</groupId> <artifactId>springclud-api-common</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <!-- 引入zookeeper客户端 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zookeeper-discovery</artifactId> <exclusions> <exclusion> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>3.4.13</version> </dependency> </dependencies>
在上面的依赖种,我要说明一点:其中我们引入springcloud zookeeper的依赖,它底层还依赖属于zookeeper本身的jar包,如果你zookeeper服务器的版本和它自带的版本不一致,则会版本冲突的问题,我的zookeeper是3.4.13,所以把它自带给排出去了,用对应版本的zookeeper依赖。
3.改配置
server:
port: 8004
# 服务别名---zookeeper注册中心名称
spring:
application:
name: cloud-provider-payment
cloud:
zookeeper:
connect-string: 192.168.xx.xxx:2181
4.主启动
@SpringBootApplication @EnableDiscoveryClient public class PaymentApplication8004 { public static void main(String[] args) { SpringApplication.run(PaymentApplication8004.class, args); } }
eureka那个注解就不再需要了,但是@EnableDdiscoveryClient一定得有,好几个注册中心都需要用到这个注解来保证服务注册到注册中心里
5.业务类
@RestController @Slf4j public class PaymentController { @Value("${server.port}") private String serverPort; @RequestMapping(value = "/payment/zk") public String paymentzk(){ return "springcloud with zookeeper: " + serverPort + " " + UUID.randomUUID().toString(); } }
6.测试;启动该模块,然后到linux的服务器查看,如下:
OK,最后在讲下我们服务注册到zookeeper中,是属于临时节点还是持久节点,答案是临时节点。当我们服务停了,zookeeper在短时间内不会移除,但过了时间就它的节点剔除掉。