Zookeeper服务注册与发现
Zookeeper安装与Linux系统
1. Zookeeper注册中心
zookeeper是一个分布式协调工具,可以实现注册中心功能;连接zookeeper注册中心时要关闭Linux服务器防火墙后启动zooleeper服务器或者Linux暴露端口;zookeeper服务器取代Eureka服务器,zk作为服务注册中心。
2. 服务提供者cloud-provider-payment8004
pom文件:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
</dependency>
application.yaml:
server:
port: 8004
spring:
application:
name: cloud-provider-payment
cloud:
zookeeper:
connect-string: 192.168.25.153:2181
主启动类:
@SpringBootApplication
@EnableDiscoveryClient
public class PaymentMain8004 {
public static void main(String[] args) {
SpringApplication.run(PaymentMain8004.class,args);
}
}
controller层:
@RestController
@Slf4j
public class PaymentController {
@Value("${server.port}")
private String serverPort;
@RequestMapping(value = "/payment/zk")
public String paymentzk(){
return "spring cloud with zookeeper:"+serverPort+"\t"+ UUID.randomUUID().toString();
}
}
启动报错:
jar包冲突,安装于linux上的zookeeeper与jar的版本不同。修改pom文件:
<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.9</version>
</dependency>
测试:
Zookeeper上面是临时节点还是持久?zookeeper是临时节点,每一次停的之后,在启动会生成新流水号。
3. 服务消费者cloud-consumerzk-order80
-
pom文件跟cloud-provider-payment8004一样
-
application.yaml配置一样,除端口之外
-
主启动类一样
-
config层
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
-
controller层
@RestController
@Slf4j
public class OrderController {
public static final String INVOKE_URL="http://cloud-provider-payment";
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/info")
public String getPaymentInfo(){
String result=restTemplate.getForObject(INVOKE_URL+"/payment/zk",String.class);
return result;
}
}
测试: