Nacos学习笔记(三)----服务消费方式
方式一: loadBalancerClient+restTemplate拼接路径方式
/*spring cloud common提供的服务治理接口,负载均衡客户端*/
@Autowired
LoadBalancerClient loadBalancerClient;
/*原始方式:拼接路径*/
@GetMapping("/test1")
public String test() {
RestTemplate restTemplate = new RestTemplate();
/*choos函数:负载均衡的选出一个服务实例*/
ServiceInstance serviceInstance = loadBalancerClient.choose("test-nacos-server");
/*拼接方式一:*/
System.out.println("http://" + serviceInstance.getHost() + ':' + serviceInstance.getPort() + "/test?msg=nacos");
/*拼接方式二:*/
String url = serviceInstance.getUri() + "/test?msg=nacos";
String result = restTemplate.getForObject(url, String.class);
String msg = url + "---- return : " + result;
System.out.println(msg);
return msg;
}
方式二: restTemplate加入@LoadBalanced注解
@Autowired
RestTemplate restTemplate;
/*注解方式:填写请求路径*/
@GetMapping("/test2")
public String test2() {
/*直接请求服务名*/
String url = "http://test-nacos-server/test?msg=restTemplate";
String res = restTemplate.getForObject(url, String.class);
System.out.println(res);
return res;
}
@Bean
/*增加@LoadBalanced注解*/
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
方式三: loadBalancerClient+ WebClient(spring 5引入)拼接路径方式
1.pom修改:将spring-boot-starter-web改为spring-boot-starter-webflux
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
2.WebClient相关信息以及实例可以看官网(有示例比较好)
3.基本方法
4.代码:
/*spring cloud common提供的服务治理接口,负载均衡客户端*/
@Autowired
LoadBalancerClient loadBalancerClient;
/*spring 5 提供的webclient*/
@GetMapping("/test3")
public Mono<String> test3() {
ServiceInstance instance = loadBalancerClient.choose("test-nacos-server");
String url = instance.getUri() + "/test?msg=nacos";
/*构建方式一(简单版):create*/
Mono<String> mono = WebClient.create(url).get().retrieve().bodyToMono(String.class);
/*构建方式二:builder*/
Mono<String> toMono = WebClient.builder().baseUrl(url).build().get().retrieve().bodyToMono(String.class);
System.out.println(url);
return toMono;
}
*为了测试后面的方式是否负载,把服务提供方稍微改了一下:
方式四: webclient加入@LoadBalanced注解
@Bean
@LoadBalanced
/*构造webclient,加入@LoadBalanced注解*/
public WebClient.Builder webClientBuilder() {
return WebClient.builder();
}
@Autowired
private WebClient.Builder webClientBuilder;
@GetMapping("/test4")
public Mono<String> test4() {
String url = "http://test-nacos-server/test?msg=restTemplate";
Mono<String> mono = webClientBuilder.build()
.get()
.uri(url)
.retrieve()
.bodyToMono(String.class);
return mono;
}
方式五: feign
1.pom添加:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.创建Feign客户端(接口)
@FeignClient("test-nacos-server")
public interface ClientForFeign {
@GetMapping("/test")
String test(@RequestParam(name = "msg") String msg);
}
3.加入@EnableFeignClients注解,开启扫描Spring Cloud Feign客户端的功能
4.在Controller中实现
@Autowired
private ClientForFeign clientForFeign;
@GetMapping("/test5")
public String test5() {
String s = clientForFeign.test("nacos");
return s;
}