1-使用RestTemplate
@Slf4j
@RestController
public class TestController {
@Autowired
RestTemplate restTemplate;
@GetMapping("/test")
public String test() {
String result = restTemplate.getForObject("http://nacos-producer/hello?name=ChadJ", String.class);
return "Return : " + result;
}
}
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
利用@LoadBalanced在调用接口的时候拦截下来,然后进行负载均衡调用。
2-使用WebClient
@Slf4j
@RestController
public class TestController {
@Autowired
private WebClient.Builder webClientBuilder;
@GetMapping("/test")
public Mono<String> test() {
Mono<String> result = webClientBuilder.build()
.get()
.uri("http://alibaba-nacos-discovery-server/hello?name=didi")
.retrieve()
.bodyToMono(String.class);
return result;
}
}
@Bean
@LoadBalanced
public WebClient.Builder loadBalancedWebClientBuilder() {
return WebClient.builder();
}
3-使用Feign
- 引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.主类@EnableFeignClients
3.定义Fegin客户端和使用Fegin客户端
@Slf4j
@RestController
public class TestController {
@Autowired
Client client;
@GetMapping("/test")
public String test() {
String result = client.hello("didi");
return "Return : " + result;
}
}
@FeignClient("alibaba-nacos-discovery-server")
interface Client {
@GetMapping("/hello")
String hello(@RequestParam(name = "name") String name);
}
网友评论