首先安装zookeeper,这里就不多说了。
然后配置idea插件。
将服务提供者注册到zookeeper上。
pom
<?xml version="1.0" encoding="UTF-8"?>
yml文件
server: port: 8004spring: application: name: cloud-provider-payment cloud: zookeeper: connect-string: 8.142.171.23:2181
主启动类
@SpringBootApplication@EnableDiscoveryClientpublic class ProviderMain8004 { public static void main(String[] args) { SpringApplication.run(ProviderMain8004.class,args); }}
Controller
@RestController@Slf4jpublic 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
<?xml version="1.0" encoding="UTF-8"?>
yml
server: port: 80spring: application: name: cloud-consumer-service cloud: zookeeper: connect-string: 8.142.171.23:2181
主启动类
@SpringBootApplicationpublic class ConsumerZkMain80 { public static void main(String[] args) { SpringApplication.run(ConsumerZkMain80.class,args); }}
Controller
@RestController@Slf4jpublic 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
@Configurationpublic class ApplicationContextConfig { @Bean @LoadBalanced public RestTemplate getRestTemplate(){ return new RestTemplate(); }}
测试