title: ‘SpringCloudAlibaba-3-nacos服务注册与发现整合feign:webflux调用’
date: 2020-01-26 22:36:11
tags:

SpringCloudAlibaba

1.Feign

Feign是从Netflix中分离出来的轻量级项目,能够在类接口上添加注解,成为一个RES API客户端。

2.OpenFegin

Spring Cloud在netflix feign的基础上扩展了支持Spring MVC注解,并通过自动配置为Spring Boot应用程序提供快速集成。

3.使用Fegin

1.复制nacos-discovery-consumer项目,修改maven坐标及其在父工程里面添加module即可。
2.在nacos-discovery-consumer-fegin引入fegin依赖

1
2
3
4
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

3.开启feign

1
2
3
4
5
6
7
8
9
10
11
12
13
@EnableFeignClients
@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerFeignApplication {
public static void main(String[] args) {
SpringApplication.run(NacosDiscoveryConsumerFeignApplication.class, args);
}
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}

4.nacos-discovery-consumer-fegin调用nacos-discovery-provider

a.创建feign的cient端口,并且其是nacos-discovery-provider的调用接口

接口:HelloFeignService

1
2
3
4
5
6
7
8
9
//FeignClient注解里面填写的是provider服务名称
@FeignClient("nacos-discovery-provider")
public interface HelloFeignService {
@GetMapping("/hello")
String hello(@RequestParam("name") String name);
}
```
类:TestController

@RestController
public class TestController {
@Autowired
private HelloFeignService helloFeignService;
@GetMapping(“/test”)
public String test(String name){
return helloFeignService.hello(name);
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
测试:
http://127.0.0.1:8052/test?name=111
返回:
Hello 111 port:8051
### 4.webflux
webflux是和Spring-webmvc进行的对比,如下:
![](https://raw.githubusercontent.com/startshineye/img/master/2020/01/26.png)
步骤:
1. 1.引入webflux的依赖
我们创建nacos-discovery-consumer-webflux;
修改里面的pom.xml文件:


org.springframework.boot
spring-boot-starter-web

1
2
为:


org.springframework.boot
spring-boot-starter-webflux

1
2
3
2. 2.创建WebClient.Builder(类似于mvc中的restTemplate)

@EnableDiscoveryClient
@SpringBootApplication
public class NacosDiscoveryConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(NacosDiscoveryConsumerApplication.class, args);
}
@Bean
@LoadBalanced
public WebClient.Builder webClientBuilder(){
return WebClient.builder();
}
}

1
2
3. 3.Controller中调用

@RestController
public class TestController {
@Autowired
private WebClient.Builder webClientBuilder;
@GetMapping(“/test”)
public Mono test(String name){
return webClientBuilder.build()
.get()
.uri(“http://nacos-discovery-provider/hello?name=“ + name)
.retrieve()
.bodyToMono(String.class);
}
}
```

毕业于<br>相信技术可以改变人与人之间的生活<br>码农一枚