前言:承接上一章节《Nacos discovery》 ,在 Nacos discovery 基础上集成openFeign
1、修改调用方配置文件
1.1、增加springcloud依赖
<dependencyManagement> <dependencies> <!--spring cloud 依赖--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>2021.0.5</version> <type>pom</type> <scope>import</scope> </dependency> <!--spring cloud alibaba 依赖--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2021.0.4.0</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>
1.2、增加openFeign依赖项
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-loadbalancer --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency> </dependencies>
2、调用方代码改造
2.1、在启动类增加openFeign配置
@EnableFeignClients
2.2、新增服务层接口:UserService
import com.xxx.common.entity.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; @FeignClient(name = "app-provider-service") public interface UserService { @GetMapping("/user/getUserName") public User getUserName() ; }
2.3、改造控制层方法:
@Autowired private UserService userService; @GetMapping("/getUserName") public Map getUserName() { User user = userService.getUserName(); Map map = new HashMap(); map.put("code" , 200); map.put("data" , user); map.put("type" , "caller"); return map; }