[从零开始的账本项目07] 前后端分离, 创建consumer模块

291 阅读1分钟

在之前的模块中, 通过"分布式", 完成了众多的provider模块, 接下来就是创建consumer模块, 暴露给前端进行使用. 本次consumer模块决定采用openFeign进行对应微服务的访问.

根据之前的模块. 共有四个微服务, 分别是:

  • bngelbook-user-provider
  • bngelbook-book-provider
  • bngelbook-account-provider
  • bngelbook-bill-provider

由于创建consumer模块的方法大差不差. 因此选出其中的一个进行展示.
假定选择的模块为bngel-user-consumer.

首先是引入对应openFeign的依赖.

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

使用方式:

  1. 创建对应微服务的service接口类.
    在接口类上使用@FeignClient注解标明使用的微服务名,
    使用@Service将其注入Spring.
@FeignClient("bngelbook-user-provider")
@Service
public interface UserService {

    @PostMapping("/user")
    CommonResult saveUser(@RequestBody User user);

    @DeleteMapping("/user")
    CommonResult deleteUserById(@RequestParam("id") Long id);

    @PutMapping("/user")
    CommonResult updateUserById(@RequestBody User user);

    @GetMapping("/user")
    CommonResult getUserById(@RequestParam("id") Long id);

    @PostMapping("/user/login")
    CommonResult login(@RequestParam("account") String account,
                       @RequestParam("password") String password);
}
  1. 之后在相应controller类中即可直接注入进行使用
@Autowired
private UserService userService;

剩余部分便与provider中的controller类几乎一致.

  1. 在主启动类上标注@EnableFeignClients即可启动部署.

欢迎各位来对我的小项目提出各种宝贵的意见, 这对我的进步非常重要, 谢谢大家.
GitHub地址: Bngel/bngelbook