Feign:一个声明式的REST客户端,它能让REST调用更加简单。
参考:https://blog.csdn.net/admin_15082037343/article/details/106959438
在demo-client中添加依赖 <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> 启动类添加注解@EnableFeignClients package com.demo.client; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; @SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class ClientApplication { public static void main(String[] args) { SpringApplication.run(ClientApplication.class, args); } } 新增接口UserClient package com.demo.client.api; import com.demo.client.entity.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.*; @FeignClient(value = "demo-provider", path = "/user") public interface UserClient { @GetMapping Object findUser(@RequestParam("pageNo") Integer pageNo, @RequestParam("size") Integer size); @PostMapping User save(@RequestBody User user); @GetMapping("/{id}") User findById(@PathVariable("id") String id); @DeleteMapping("/{id}") String deleteById(@PathVariable("id") String id); }findUser()方法返回Object在这里只是为了方便,可以自己封装实体类。 @FeignClient:value代表访问的应用,path:请求路径的统一前缀。
UserController更新如下 package com.demo.client.controller; import com.demo.client.api.UserClient; import com.demo.client.entity.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; @RestController @RequestMapping("/user") public class UserController { @Autowired private UserClient userClient; @GetMapping public Object findUser(@RequestParam(required = false, defaultValue = "1") Integer pageNo , @RequestParam(required = false, defaultValue = "10") Integer size) { return userClient.findUser(pageNo, size); } @RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }) public User save(@RequestBody User user) { return userClient.save(user); } @GetMapping("/{id}") public User findById(@PathVariable String id) { return userClient.findById(id); } @DeleteMapping("/{id}") public String deleteById(@PathVariable String id) { userClient.deleteById(id); return id; } }在这里就不使用RestTemplate对象去调用接口了,而是使用UserClient替换,替换之后代码更简单了。
左边为使用RestTemplate调用接口,右边为Feign调用接口。
此时访问接口发现控制台打印日志如下
https://github.com/phone15082037343/demo.git