使用Feign客户端与远程API进行通信的过程包括以下几个步骤:

1. 引入Feign依赖

首先,需要在你的项目中引入Feign的依赖。在pom.xml中添加以下依赖:

1
2
3
4
xml复制代码<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2. 启用Feign客户端

在你的Spring Boot应用的启动类上添加@EnableFeignClients注解来启用Feign客户端:

1
2
3
4
5
6
7
8
9
10
11
java复制代码import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}

3. 定义Feign客户端接口

按照你的需求定义Feign客户端接口,并使用@FeignClient注解进行配置。例如,假设我们有一个用户中心API,定义如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
java复制代码package com.xxy.usercenter.openfegin.client;

import com.xt.jwt.bridge.model.AccountKeyInfoVO;
import com.xt.zeus.lang.util.Result;
import com.xxy.usercenter.openfegin.config.FeignConfiguration;
import com.xxy.usercenter.openfegin.model.dto.BaseUserDTO;
import com.xxy.usercenter.openfegin.model.dto.UserLoginDTO;
import com.xxy.usercenter.openfegin.model.response.BaseUserResponse;
import io.swagger.annotations.ApiOperation;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@FeignClient(
name = "${feign.user-api.name}",
url = "${feign.user-api.url}",
configuration = {FeignConfiguration.class}
)
public interface UserCenterClient {
@ApiOperation("登录")
@PostMapping("/user/login")
Result<Map<String, Object>> login(@RequestBody @Validated UserLoginDTO userLoginDTO);

@ApiOperation("注册")
@PostMapping("/user/register")
Result<Map<String, Long>> register(@RequestBody @Validated BaseUserDTO baseUserDTO);

@ApiOperation("根据token验证用户")
@GetMapping("/user/account")
Result<AccountKeyInfoVO> getAccountDetail(@RequestParam("token") String token);

@ApiOperation("根据id查询用户信息")
@GetMapping("/user/{userId}")
Result<BaseUserResponse> getUserById(@PathVariable("userId") Long userId);

// 其他方法...
}

4. 配置Feign客户端

你可以在配置文件(如application.ymlapplication.properties)中配置Feign客户端的属性:

1
2
3
4
yaml复制代码feign:
user-api:
name: user-center
url: http://user-center-api-url

5. 使用Feign客户端

在需要调用远程API的服务类中,注入Feign客户端接口并调用其方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
java复制代码import com.xxy.usercenter.openfegin.client.UserCenterClient;
import com.xxy.usercenter.openfegin.model.dto.UserLoginDTO;
import com.xt.zeus.lang.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserService {

@Autowired
private UserCenterClient userCenterClient;

public Result<Map<String, Object>> login(UserLoginDTO userLoginDTO) {
return userCenterClient.login(userLoginDTO);
}

public Result<Map<String, Long>> register(BaseUserDTO baseUserDTO) {
return userCenterClient.register(baseUserDTO);
}

public Result<AccountKeyInfoVO> getAccountDetail(String token) {
return userCenterClient.getAccountDetail(token);
}

public Result<BaseUserResponse> getUserById(Long userId) {
return userCenterClient.getUserById(userId);
}

// 其他方法...
}

6. 处理结果

Feign客户端方法返回的结果通常会被封装在一个通用的响应对象中,如Result<T>。你可以直接处理这个响应对象,获取其中的数据或处理错误。

1
BaseUserResponse user = userCenterClient.getUserById(userId).getData();

总结

通过上述步骤,你可以在Spring Boot项目中使用Feign客户端轻松地与远程API进行通信。Feign的声明式客户端使得HTTP API调用变得更加简单和可读,同时支持多种配置选项和扩展性。

用户中心api:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.xxy.usercenter.openfegin.client;

import com.xt.jwt.bridge.model.AccountKeyInfoVO;
import com.xt.zeus.dao.jdbc.hql.Page;
import com.xt.zeus.lang.util.Result;
import com.xxy.usercenter.openfegin.config.FeignConfiguration;
import com.xxy.usercenter.openfegin.model.dict.UserAuthority;
import com.xxy.usercenter.openfegin.model.dto.BaseUserDTO;
import com.xxy.usercenter.openfegin.model.dto.UserLoginDTO;
import com.xxy.usercenter.openfegin.model.request.PasswordModifyRequest;
import com.xxy.usercenter.openfegin.model.request.ReviewTreeReq;
import com.xxy.usercenter.openfegin.model.request.UnitByTypeRequest;
import com.xxy.usercenter.openfegin.model.request.UnitByUnitIdsRequest;
import com.xxy.usercenter.openfegin.model.request.UnitUsersRequest;
import com.xxy.usercenter.openfegin.model.request.UserByNameRequest;
import com.xxy.usercenter.openfegin.model.request.login.LoginGroup;
import com.xxy.usercenter.openfegin.model.request.page.ClientPageRequest;
import com.xxy.usercenter.openfegin.model.request.page.UserPageRequest;
import com.xxy.usercenter.openfegin.model.response.BaseClientResponse;
import com.xxy.usercenter.openfegin.model.response.BaseUnitResponse;
import com.xxy.usercenter.openfegin.model.response.BaseUnitUser;
import com.xxy.usercenter.openfegin.model.response.BaseUserResponse;
import com.xxy.usercenter.openfegin.model.response.CheckUserResponse;
import com.xxy.usercenter.openfegin.model.response.ReviewTreeNodeResp;
import com.xxy.usercenter.openfegin.model.vo.AllocateAuthorityRequest;
import com.xxy.usercenter.openfegin.model.vo.UnitListByUnitIdVo;
import com.xxy.usercenter.openfegin.model.vo.UserByIdCardVo;
import com.xxy.usercenter.openfegin.model.vo.UserConditionRequest;
import com.xxy.usercenter.openfegin.model.vo.UserTypeVo;
import com.xxy.usercenter.openfegin.util.TreeUtil;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.cloud.openfeign.SpringQueryMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.multipart.MultipartFile;

@FeignClient(
name = "${feign.user-api.name}",
url = "${feign.user-api.url}",
configuration = {FeignConfiguration.class}
)
public interface UserCenterClient {
@ApiOperation("登录")
@PostMapping({"/user/login"})
Result<Map<String, Object>> login(@RequestBody @Validated({LoginGroup.class}) UserLoginDTO userLoginDTO);

@ApiOperation("注册")
@PostMapping({"/user/register"})
Result<Map<String, Long>> register(@RequestBody @Valid BaseUserDTO baseUserDTO);

@ApiOperation("刷新token")
@GetMapping({"/user/refreshToken"})
Result<Map<String, Object>> refreshToken(@RequestParam("refreshToken") @Valid @NotBlank String refreshToken);

@ApiOperation("根据token验证用户")
@GetMapping({"/user/account"})
Result<AccountKeyInfoVO> getAccountDetail(@RequestParam("token") @Valid @NotBlank String token);

@ApiOperation("查看所有的单位")
@GetMapping({"/unit/getAllUnit"})
Result<List<BaseUnitResponse>> getAllUnit(@RequestParam("clientCode") String clientCode);

@ApiOperation("根据unitid集合,查询所有的单位集合")
@GetMapping({"/unit/getUnitByUnitIds"})
Result<List<BaseUnitResponse>> getUnitByUnitIds(@SpringQueryMap UnitByUnitIdsRequest unitByUnitIdsRequest);

@ApiOperation("模糊匹配user")
@GetMapping({"/user/getUserByIds"})
Result<List<BaseUserResponse>> getUserByIds(@SpringQueryMap UserConditionRequest vo);

@ApiOperation("根据身份证查询用户信息")
@GetMapping({"/user/getUserByIdCard"})
Result<CheckUserResponse> getUserByIdCard(@SpringQueryMap UserByIdCardVo no);

@ApiOperation("通过身份证获取验证人员类型")
@GetMapping({"/user/getUserType"})
Result<UserAuthority> getUserType(@SpringQueryMap UserTypeVo vo);

@ApiOperation("根据单位编码,系统编码分页查询人员列表")
@GetMapping({"/user/getUserPage"})
Result<Page<BaseUserResponse>> getUserPage(@SpringQueryMap UserPageRequest userPageRequest);

@ApiOperation("根据clientId分页查询人员列表")
@GetMapping({"/user/client"})
Result<Page<BaseUserResponse>> getClient(@SpringQueryMap UserPageRequest userPageRequest);

@ApiOperation("根据clientCode获取所有可见单位列表")
@GetMapping({"/unit/getUnitByClientCode"})
Result<List<TreeUtil.TreeNode>> getUnitByClientCode(@RequestParam("clientCode") String clientCode);

@ApiOperation("根据单位id获取单位信息")
@GetMapping({"/unit/{unitId}"})
Result<BaseUnitResponse> getByUnitId(@PathVariable("unitId") Long unitId);

@ApiOperation("根据id查询用户信息")
@GetMapping({"/user/{userId}"})
Result<BaseUserResponse> getUserById(@PathVariable("userId") Long userId);

@ApiOperation("根据单位id获取子单位列表(包含当前单位id,非树结构)")
@GetMapping({"/unit/getRelationUnit"})
Result<List<BaseUnitResponse>> getUnitListByUnitId(@SpringQueryMap UnitListByUnitIdVo vo);

@ApiOperation("根据名称(人员姓名、单位名称)模糊查询内部人员列表")
@GetMapping({"/user/getUserByName"})
Result<List<BaseUserResponse>> getUserByName(@SpringQueryMap UserByNameRequest request);

@ApiOperation("根据unitIds、userIds 查询部门人员树")
@GetMapping({"/user/getUnitUserTree"})
Result<List<ReviewTreeNodeResp>> getUnitUserTree(@SpringQueryMap ReviewTreeReq request);

@ApiOperation("获取当前系统可见-单位人员树结构")
@GetMapping({"/user/getUnitUserTreeNew"})
Result<List<ReviewTreeNodeResp>> getUnitUserTreeNew(@RequestParam(value = "clientCode",required = false) String clientCode);

@ApiOperation("根据unitType 查询部门列表")
@GetMapping({"/unit/getUnitListByType"})
Result<List<BaseUnitResponse>> getUnitListByType(@SpringQueryMap UnitByTypeRequest request);

@ApiOperation("根据用户id列表/单位id列表查询用户单位信息")
@GetMapping({"/unit/getUnitUser"})
Result<List<BaseUnitUser>> getUnitUser(@SpringQueryMap UnitUsersRequest request);

@ApiOperation("分配用户可见系统权限(子系统)")
@PostMapping({"/client/allocate"})
Result<Boolean> allocateAuthority(@SpringQueryMap AllocateAuthorityRequest request);

@ApiOperation("根据系统编码查询系统可见人员")
@GetMapping({"/user/getUserByClientCode"})
Result<List<BaseUserResponse>> getUserByClientCode(@RequestParam("clientCode") String clientCode);

@ApiOperation("根据clientCode查询")
@GetMapping({"/client/getByclientCode"})
Result<List<BaseClientResponse>> getByClientCode(@Validated @NotEmpty Set<String> clientCodes);

@ApiOperation("分页查询系统列表")
@GetMapping({"/client"})
Result<Page<BaseClientResponse>> queryPage(@Validated ClientPageRequest pageRequest);

@ApiOperation("上传用户头像")
@PostMapping(
value = {"/user/uploadAvatar"},
consumes = {"multipart/form-data"}
)
Result<?> uploadAvatar(@RequestPart("avatar") MultipartFile avatar, @RequestParam("userId") Long userId);

@ApiOperation("修改/重置密码")
@PutMapping({"/user/password"})
Result<?> reset(@RequestBody @Validated PasswordModifyRequest request);

@ApiOperation("根据单位id列表获取子单位列表(包含当前单位id,非树结构)")
@GetMapping({"/unit/getRelationUnitList"})
Result<List<BaseUnitResponse>> getUnitListByUnitIds(@SpringQueryMap UnitByUnitIdsRequest request);

@ApiOperation("根据部门id查询其下所有用户(包含所有子部门)")
@GetMapping({"/user/getUnitChildrenUser"})
Result<List<BaseUserResponse>> getUnitChildrenUser(@SpringQueryMap UnitListByUnitIdVo vo);
}

用户中心用法示例:

1.根据单个用户id获取用户

1
BaseUserResponse user = userCenterClient.getUserById(taskVO.getUser()).getData();

2.根据多个用户id获取用户

1
2
Map<Long, BaseUserResponse> userMap = userCenterClient.getUserByIds(UserConditionRequest.builder().userIds(userIdList).clientCode(ClientConstants.SYSTEM_CODE).build()).getData()
.stream().collect(Collectors.toMap(BaseUserResponse::getId, baseUserResponse -> baseUserResponse));