首先安装zookeeper,这里就不多说了。
然后配置idea插件。
将服务提供者注册到zookeeper上。
pom
SpringCloud-2020 com.mql 1.0-SNAPSHOT 4.0.0 Provider-8004 com.mql cloud-api-commons 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.springframework.cloud spring-cloud-starter-zookeeper-discovery org.apache.zookeeper zookeeper org.apache.zookeeper zookeeper 3.4.9 org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test
yml文件
server:
port: 8004
spring:
application:
name: cloud-provider-payment
cloud:
zookeeper:
connect-string: 8.142.171.23:2181
主启动类
@SpringBootApplication
@EnableDiscoveryClient
public class ProviderMain8004 {
public static void main(String[] args) {
SpringApplication.run(ProviderMain8004.class,args);
}
}
Controller
@RestController
@Slf4j
public class PaymentController {
@Value("${server.port}")
private String serverPort;
@GetMapping(value = "/payment/zk")
public String paymentzk(){
return "springcloud with zookeeper:"+serverPort+"t"+ UUID.randomUUID().toString();
}
}
启动测试
http://localhost:8004/payment/zk
zookeeper下多了一个服务,zookeeper下的节点是临时节点。
pom
SpringCloud-2020 com.mql 1.0-SNAPSHOT 4.0.0 Consumer-zk-80 com.mql cloud-api-commons 1.0-SNAPSHOT org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-starter-actuator org.springframework.cloud spring-cloud-starter-zookeeper-discovery org.apache.zookeeper zookeeper org.apache.zookeeper zookeeper 3.4.9 org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test
yml
server:
port: 80
spring:
application:
name: cloud-consumer-service
cloud:
zookeeper:
connect-string: 8.142.171.23:2181
主启动类
@SpringBootApplication
public class ConsumerZkMain80 {
public static void main(String[] args) {
SpringApplication.run(ConsumerZkMain80.class,args);
}
}
Controller
@RestController
@Slf4j
public class ConsumerController {
public static final String INVOME_URL = "http://cloud-provider-payment";
@Resource
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/zk")
public String payment (){
String result = restTemplate.getForObject(INVOME_URL+"/payment/zk",String.class);
return result;
}
}
RestTemplate
@Configuration
public class ApplicationContextConfig {
@Bean
@LoadBalanced
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
}
测试



