Zookeeper服务注册与发现
gitee:springcloud_study: springcloud:服务集群、注册中心、配置中心(热更新)、服务网关(校验、路由、负载均衡)、分布式缓存、分布式搜索、消息队列(异步通信)、数据库集群、分布式日志、系统监控链路追踪。
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-paymentcloud: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@LoadBalancedpublic RestTemplate getRestTemplate(){return new RestTemplate();}
}
-
controller层
@RestController
@Slf4j
public class OrderController {public static final String INVOKE_URL="http://cloud-provider-payment";
@Resourceprivate RestTemplate restTemplate;
@GetMapping("/consumer/info")public String getPaymentInfo(){String result=restTemplate.getForObject(INVOKE_URL+"/payment/zk",String.class);return result;}
}
测试: