代码
支付服务payment-zk-8003
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
</dependencies>
配置文件application.yaml
server:
port: 8003
spring:
application:
name: cloud-zookeepr-payment #注册进zookeeper使用的微服务节点名称
cloud:
zookeeper:
connect-string: 106.15.60.91:2181 #zookeeper服务注册中心的地址,如果有多个注册中心,用逗号分隔开
启动类
@SpringBootApplication
@EnableDiscoveryClient //开启服务发现,zookeeper和consul都需要的一个注解
public class ApplicationContextMain8003 {
public static void main(String[] args) {
SpringApplication.run(ApplicationContextMain8003.class);
}
}
业务代码
@RestController
public class PaymentController {
@Autowired
PaymentService paymentService;
@Value("${server.port}")
String port;
@GetMapping("/payment/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") int id){
Payment payment = paymentService.getPaymentById(id);
return new CommonResult(200, "success:" + port, payment);
}
}
订单服务order-zk80
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
</dependencies>
配置文件application.yaml
server:
port: 80
spring:
application:
name: cloud-zookeeper-order #注册进zookeeper使用的微服务节点名称
cloud:
zookeeper:
connect-string: 106.15.60.91:2181 #zookeeper服务注册中心的地址,如果有多个注册中心,用逗号分隔开
启动类
@SpringBootApplication
@EnableDiscoveryClient //开启服务发现,zookeeper和consul都需要的一个注解
public class ApplicationContextMain80 {
public static void main(String[] args) {
SpringApplication.run(ApplicationContextMain80.class);
}
}
业务代码
@RestController
public class OrderController {
@Autowired
RestTemplate restTemplate;
//已注册到zookeeper的支付微服务节点的名称
public static final String url = "http://cloud-zookeepr-payment";
@GetMapping("/order/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") int index) {
return restTemplate.getForObject(url + "/payment/" + index, CommonResult.class, (Object) null);
}
}
zookeeper版本冲突
当引入的zookeeper依赖jar包版本高于服务器安装的的zookeeper版本时,启动微服务时会报错
查看引入的jar依赖版本
我服务器zookeeper版本是3.6.1,因此并不会报错,如果报错了只需要先排除冲突的zookeeper依赖,再引入低版本依赖
<dependencies>
<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>
//引入低于服务器zookeeper版本的依赖
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.9</version>
</dependency>
</dependencies>