SpringCloud-Gateway无法使用Feign服务(2021.X版本)

Spring Cloud Gateway 2021.x版本,无法使用Feign调用其他服务接口。

问题原因:

在官网的 issue 里面找到了相关的问题。

How to call another micro-service on GatewayFilterFactory ? · Issue #1090 · spring-cloud/spring-cloud-gateway · GitHubHello, Can you tell me how to call another micro-service on a GatewayFilterFactory? I want to call the authentication micro-service when a request come from user. 1st, I tried to use feign client. but I can not get the ServletRequestAttr...https://github.com/spring-cloud/spring-cloud-gateway/issues/1090

Spring Cloud Gateway 2021.x版本 基于WebFlux实现,使用webclient 替换 feign。

使用案例:

java 复制代码
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * @Author: meng
 * @Description: 权限工具类
 * @Date: 2023/8/3 15:01
 * @Version: 1.0
 */
@Component
public class AuthUtils {

	private static Logger logger = LoggerFactory.getLogger(AuthUtils.class);

	public final static String LB = "lb://";

	@Autowired
	private WebClient.Builder webBuilder;

	public String getAesKeyByAppId(String appId) {
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("appId", appId);
		try {
			Mono<String> result = webBuilder.baseUrl(LB + "服务名称")
				.build()
				.post()
				.uri("uri")
				.contentType(MediaType.APPLICATION_JSON)
				.header(HttpHeaders.AUTHORIZATION, "token")
				.bodyValue(jsonObject)
				.retrieve()
				.bodyToMono(String.class);
			String body = result.toFuture().get();
			logger.info("body:{}", body);
			// 处理逻辑
			...
		}
		catch (Exception e) {
			logger.error("Exception:{}", e);
		}
		return null;
	}

}
相关推荐
不凡而大米、1 分钟前
报错:传入的请求具有过多的参数。该服务器支持最多2100个参数
java·开发语言·mybatis
木风小助理5 分钟前
QPS监控:SpringBoot应用性能监控的必要性与实践
java·spring boot·后端
打工的小王5 分钟前
单例模式的实现
java·开发语言·单例模式
是宇写的啊6 分钟前
单例模式-阻塞队列
java·开发语言·单例模式
u0104058367 分钟前
Java中的单例模式详解
java·开发语言·单例模式
霸道流氓气质9 分钟前
SpringBoot+modbus4j实现ModebusTCP通讯定时读取多个plc设备数并存储进redis中
java·spring boot·redis·modbustcp·plc
历程里程碑11 分钟前
哈希1:两数之和:哈希表优化指南
java·开发语言·数据结构·c++·算法·哈希算法·散列表
小唐同学爱学习12 分钟前
布隆过滤器
java·spring boot·中间件
码界奇点13 分钟前
Tomcat与JDK版本对照全解析避坑指南生产环境选型建议
java·开发语言·容器·jdk·tomcat
Remember_99318 分钟前
【数据结构】深入理解排序算法:从基础原理到高级应用
java·开发语言·数据结构·算法·spring·leetcode·排序算法