赞
踩
前言:Spring cloud微服务架构现在是最为流行的开发架构之一,它想要开发一种由多个小服务组成的应用。每个服务运行于独立的进程,并且采用轻量级交互。
那么我们如何实现各个模块之间的调用呢?
1.这里本地注册模块为interact-service
,调用模块为user-service
:
1.导入依赖:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.在本地模块新建一个接口类,用于映射user-service模块中的接口:
@FeignClient(value = "user-service", fallback = UserClientFallback.class) public interface UserClient { // 根据id查询用户姓名 @GetMapping("/api/v1/user/find/name") HttpRespond findNameById(@RequestParam("trainUserId") int trainUserId); // 查询当前用户信息 @RequestMapping(value = "/api/v1/user/detail", method = RequestMethod.GET) HttpRespond getUserDetail(); // 根据id查询用户角色信息 @RequestMapping(value = "/api/v1/user/user_role_name_by_id", method = RequestMethod.GET) HttpRespond getRolesByUserId(@RequestParam("userId") Integer userId); }
说明:
@FeignClient
注解,来使用和发现其他模块的服务。其中value
属性的值为在eureka上已经注册服务的子服务模块名称,这里的值为user-service,fallback
属性则指定一个回调类,当发生异常错误时会回调该类中的逻辑方法:3.映射接口回调类:
@Component public class UserClientFallback implements UserClient { @Override public HttpRespond getUserDetail() { return HttpRespond.unknownException(); } @Override public HttpRespond findNameById(int trainUserId) { return HttpRespond.unknownException(); } @Override public HttpRespond getRolesByUserId(Integer userId) { return HttpRespond.unknownException(); }
4.新建一个测试Controller,测试调用接口:
@RestController @RequestMapping("/api/v1/interact/test") public class TestController { @Autowired UserClient userClient; /** * 测试用户模块中根据id查找用户名接口 * @return */ @GetMapping("/findNameById") public HttpRespond findNameById(){ HttpRespond httpRespond = userClient.findNameById(1); return httpRespond; } /** * 测试用户模块当前用户具体信息 * @return */ @GetMapping("/getUserDetail") public HttpRespond getUserDetail(){ HttpRespond httpRespond = userClient.getUserDetail(); return httpRespond; } /** * 测试用户模块根据ID查找用户角色信息 * @return */ @GetMapping("/getRolesByUserId") public HttpRespond getRolesByUserId(){ HttpRespond httpRespond = userClient.getRolesByUserId(1); return httpRespond; } }
5.在SpringBoot启动类加上@EnableFeignClients
注解,调用其他服务的api:
1.这个interact-service子模块是不含有登录处理的,所以想要我们在浏览器登录系统后在请求头拿到对应的uid以及token信息:
2.将uid与token信息加入到postman请求头中:
3.发送请求,请求成功返回数据:
至此,基于Spring Cloud微服务架构调用其他模块接口方法已经实现。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。