Zookeeper当作注册中心配置
开启Zookeeper服务
创建生产者&消费者
最基础的SpringBoot项目,提供一个方法即可,为方便测试负载均衡,创建两个生产者
//生产者项目1
@RestController
public class ProducerController {
@GetMapping("/producer/getMethod")
public String getMethod(String val){
return val+"7777";
}
}
//生产者项目2
@RestController
public class ProducerController {
@GetMapping("/producer/getMethod")
public String getMethod(String val){
return val+"8888";
}
}
项目结构如下:
修改POM
生产者和消费者项目添加GAV坐标
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zookeeper-discovery</artifactId>
<version>2.2.5.RELEASE</version>
</dependency>
修改Yml
#生产者7777 & 生产者8888
spring:
application:
name: my-producer #注册到zk的消费者名称
cloud:
zookeeper:
connect-string: 10.20.30.227:2181
#消费者6655
server:
port: 6655
spring:
application:
name: my-customer #注册到zk的消费者名称
cloud:
zookeeper:
connect-string: 10.20.30.227:2181
修改启动类
两个生产者项目
//添加注解 @EnableDiscoveryClient
@SpringBootApplication
@EnableDiscoveryClient
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class,args);
}
}
证明生产者服务是否成功注册
进入zk中,命令查询,可看到两个服务
修改消费者项目
添加配置类
package com.rb.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@Configuration
public class ApplicationContextBean
{
@Bean
@LoadBalanced //开启负载均衡
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}
添加消费者请求方法
package com.rb.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class CustomerController {
public static final String URL = "http://my-producer";
@Autowired
private RestTemplate restTemplate;
@GetMapping("/customer/getMethod")
public String getMethod(String val){
String result = restTemplate.getForObject(URL+"/producer/getMethod?val="+val, String.class);
return result;
}
}
验证消费端请求服务端
启动消费者后请求:
http://127.0.0.1:6655/customer/getMethod?val=customer
会发现会轮询输出7777和8888
链接集群ZK
三个项目Yml配置修改
server:
port: 8888
spring:
application:
name: my-producer #注册到zk的消费者名称
cloud:
zookeeper:
connect-string: 10.20.30.227:2181,10.20.30.227:2182,10.20.30.227:2183
#connect-string host1:port1,host2:port2,host3:port3