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;
	}

}
相关推荐
_codemonster10 分钟前
配置Tomcat时为啥要配置Artifacts
java·tomcat·firefox
无心水12 分钟前
2025,一路有你!
java·人工智能·分布式·后端·深度学习·架构·2025博客之星
m0_5287490012 分钟前
C语言错误处理宏两个比较重要的
java·linux·算法
独自破碎E33 分钟前
BISHI43 讨厌鬼进货
android·java·开发语言
MX_935938 分钟前
Spring xml 方式整合第三方框架总结加案例
xml·java·spring
没有bug.的程序员42 分钟前
服务网格(Istio)与传统微服务深度对垒:流量治理内核、代码侵入性博弈与运维收益实战指南
java·运维·微服务·istio·流量治理内核·代码侵入性
该叫啥44 分钟前
Spring Bean 生命周期
java·spring·servlet
星火开发设计1 小时前
虚析构函数:解决子类对象的内存泄漏
java·开发语言·前端·c++·学习·算法·知识
好大的月亮1 小时前
中值法排序及LexoRank排序算法简述
java·算法·排序算法
TongSearch1 小时前
Tongsearch分片的分配、迁移与生命周期管理
java·服务器·数据库·elasticsearch·tongsearch