Spring @FeignClient

客官°小女子只卖身不卖艺 2022-06-11 04:47 265阅读 0赞

使用Spring Cloud搭建各种微服务之后,服务可以通过@FeignClient使用和发现服务场中的其他服务。

还是以Config Server和Config Client为例,这是服务场中的注册的两个微服务。

这里写图片描述

Config Server中定义了两个服务接口(一个Post、一个Get方法)

  1. package demo.controller;
  2. import org.springframework.cloud.context.config.annotation.RefreshScope;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.PostMapping;
  5. import org.springframework.web.bind.annotation.RequestBody;
  6. import org.springframework.web.bind.annotation.RestController;
  7. import demo.model.User;
  8. @RestController
  9. @RefreshScope
  10. public class Controller {
  11. @GetMapping(value="s")
  12. String helloServer(String username) {
  13. return "Hello " + username + "!";
  14. }
  15. @PostMapping(value="u")
  16. String helloUser(@RequestBody User user) {
  17. return "Hello " + user + "!";
  18. }
  19. }

在Config Client(spring.application.name=test-dev)我们使用Config Server中定义的这两个微服务。

  1. import org.springframework.cloud.netflix.feign.FeignClient;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.PostMapping;
  4. import org.springframework.web.bind.annotation.RequestBody;
  5. import org.springframework.web.bind.annotation.RequestParam;
  6. import cn.test.bean.User;
  7. @FeignClient(value = "config-service")
  8. public interface FindService {
  9. @GetMapping(value="s")
  10. String helloServer(@RequestParam("username")String username);
  11. @PostMapping(value="u")
  12. String helloUser(@RequestBody User user);
  13. }

注意,Get方法中通过@RequestParam指定需要传递的参数,应用启动时需添加@EnableFeignClients注解。

  1. @Autowired
  2. private FindService service;
  3. @GetMapping("/find")
  4. String find(String param) {
  5. return "find " + service.helloServer(param);
  6. }
  7. @PostMapping("/f")
  8. String findU(@RequestBody User user) {
  9. return "find " + service.helloUser(user);
  10. }

调用如下:

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,265人围观)

还没有评论,来说两句吧...

相关阅读