6.2.1 使用 Eureka 的服务发现工具
引入 DIscoryClient ,用 DiscoveryClient来获取服务地址
@Autowired
DiscoveryClient discoveryClient
;
@GetMapping("/hello2")
public String
hello2() {
HttpURLConnection conn
= null
;
List
<ServiceInstance> services
= discoveryClient
.getInstances("provider");
ServiceInstance instance
= services
.get(0);
String host
= instance
.getHost();
int port
= instance
.getPort();
StringBuffer stringBuffer
= new StringBuffer();
stringBuffer
.append("http://")
.append(host
)
.append(":")
.append(port
)
.append("/hello");
try {
System
.out
.println(stringBuffer
);
URL url
= new URL(stringBuffer
.toString());
conn
= (HttpURLConnection
) url
.openConnection();
if (conn
.getResponseCode() == 200) {
BufferedReader br
= new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String s
= br
.readLine();
br
.close();
return s
;
}
} catch (MalformedURLException e
) {
e
.printStackTrace();
} catch (IOException e
) {
e
.printStackTrace();
}
return "error!";
}
访问 http://localhost:1115/hello2,验证可用
设置手工线性负载均衡
int count
= 0;
@GetMapping("/hello3")
public String
hello3() {
HttpURLConnection conn
= null
;
List
<ServiceInstance> services
= discoveryClient
.getInstances("provider");
int index
= count
++ %services
.size();
ServiceInstance instance
= services
.get(index
);
String host
= instance
.getHost();
int port
= instance
.getPort();
StringBuffer stringBuffer
= new StringBuffer();
stringBuffer
.append("http://")
.append(host
)
.append(":")
.append(port
)
.append("/hello");
try {
System
.out
.println(stringBuffer
);
URL url
= new URL(stringBuffer
.toString());
conn
= (HttpURLConnection
) url
.openConnection();
if (conn
.getResponseCode() == 200) {
BufferedReader br
= new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String s
= br
.readLine();
br
.close();
return s
;
}
} catch (MalformedURLException e
) {
e
.printStackTrace();
} catch (IOException e
) {
e
.printStackTrace();
}
return "error!";
}
验证手工线性负载均衡可用,并重复请求验证 provider 集群可用
6.2.2 简化代码
6.2.2.1 简化请求
HttpURLConnection部分代码,替换为 RestTemplate,RestTemplate 是 Spring 自带的类,不是 Spring Cloud 新增的内容。一行代码就实现 Http 调用在 main 函数中增加如下代码
@Bean
RestTemplate
restTemplateOne(){
return new RestTemplate();
}
简化前代码 简化后 再次调用 http://locahost:1115/hello2
6.2.2.1 简化负载均衡
使用 Ribbon 快速实现负债均衡,给 RestTemplate 添加 @LoadBanced 注解;在 main 函数类,新增一个 RestTemplate 的Bean对象;
@Bean
@LoadBalanced
RestTemplate
restTemplateTwo(){
return new RestTemplate();
}
因为有两个 RestTemplate Bean,在 UseHelloController 的 RestTemplate 增加 @Qualifier 注解改写前如下代码: 改写后
@Autowired
@Qualifier("restTemplateTwo")
RestTemplate balanceRestTemplate
;
@GetMapping("/hello3")
public String
hello3() {
String s
= balanceRestTemplate
.getForObject("http://provider/hello", String
.class);
return s
;
}
再次访问两次 http://localhost:1115/hello3