一、服务提供者注册进zookeeper
1、新建项目cloud-provider-payment8004
2: pom文件
<!-- SpringBoot整合zookeeper客户端 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<!--先排除自带的zookeeper3.5.3-->
<exclusions>
<exclusion>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--添加zookeeper3.4.11版本-->
<dependency>
<groupId>org.apache.zookeeper</groupId>
<artifactId>zookeeper</artifactId>
<version>3.4.11</version>
</dependency>
注意:在启动项目是会报错,原因是发生了jar包冲突,先排除自带的jar包,然后在导入zookeeper依赖。
3:配置文件
server:
port: 8004
spring:
application:
name: cloud-provider-payment
cloud:
zookeeper:
connect-string: localhost:2181
我的zookeeper直接安装在本机上,版本3.4.11
4:controller层
@RestController
public class PaymentController {
@Value("${server.port}")
private String serverPort;
@RequestMapping(value="/payment/zk")
public String paymentZK(){
return "springCloud with zookeeper: " + serverPort +"\t" + UUID.randomUUID().toString();
}
}
5:主启动类
@SpringBootApplication
// 该注解用于向使用consul或者zookeeper作为注册中心时注册服务
@EnableDiscoveryClient
public class PaymentMain8004 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8004.class, args);
}
}
6:启动zookeeper, 在启动项目
注意:zookeeper上注册的服务是临时节点,属于CAP中的CP
二、服务消费者注册进zookeeper
1:新建项目cloud-consumerzk-order80
2: pom文件和cloud-provider-payment8004一致
3:配置文件
server:
port: 80
spring:
application:
name: cloud-consumer-order
cloud:
#注册到zookeeper地址
zookeeper:
connect-string: localhost:2181
4:主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class OrderZKMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderZKMain80.class, args);
}
}
5:业务类
(1)配置类
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
(2)controller层
@RestController
public class OrderZKController {
private static final String INVOKE_URL = "http://cloud-provider-payment";
@Resource
private RestTemplate restTemplate;
@RequestMapping(value="/consumer/payment/zk")
public String getPayment(){
String result = restTemplate.getForObject(INVOKE_URL + "/payment/zk", String.class);
return result;
}
}
6:启动项目
版权声明:本文为LUNATICRUN原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。