需要创建一个服务端,至少两个客户端
三个项目启动以后
可以看到同样的application 名字CLIENTDEMO1, 有两个status.
端口号分别是:8083,8082
客户端,都有一个测试的controller
package com.bsea.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
private Logger log = LoggerFactory.getLogger(this.getClass());
@Autowired
private DiscoveryClient client;
@GetMapping("/info")
public String info() {
@SuppressWarnings("deprecation")
ServiceInstance instance = client.getLocalServiceInstance();
String info = "host:" + instance.getHost() + ",service_id:" + instance.getServiceId();
log.info(info);
return info;
}
@GetMapping("/hello")
public String hello() {
return "hello world";
}
}
测试演示
需要再创建第三个客户端,用来测试。
http://desktop-9fm4enl:9001/info
浏览器访问同一个地址,会随机的返回不同的内容。
具体代码实现
客户端1
application.yml
server:
port: 8082
spring:
application:
name: clientdemo1
eureka:
client:
register-with-eureka: true
fetch-registry: true
serviceUrl:
defaultZone: http://localhost:9888/eureka/
客户端2
server:
port: 8083
spring:
application:
name: clientdemo1
eureka:
client:
register-with-eureka: true
fetch-registry: true
serviceUrl:
defaultZone: http://localhost:9888/eureka/
客户端3 - 用来测试的消费者
server:
port: 9001
spring:
application:
name: Server-Consumer
eureka:
client:
register-with-eureka: true
fetch-registry: true
serviceUrl:
defaultZone: http://localhost:9888/eureka/
启动类
package com.bsea;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
@Bean
@LoadBalanced
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(Application.class);
}
}
测试 controller
package com.bsea.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 TestController {
@Autowired
private RestTemplate restTemplate;
@GetMapping("/info")
public String getInfo() {
return this.restTemplate.getForEntity("http://CLIENTDEMO1/info", String.class).getBody();
}
}