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

}
相关推荐
shejizuopin17 分钟前
基于SSM的高校旧书交易系统的设计与实现(任务书)
java·mysql·毕业设计·论文·任务书·基于ssm的·高校旧书交易系统的设计与实现
1candobetter25 分钟前
JAVA后端开发——Spring Boot 组件化自动配置机制
java·开发语言·spring boot
码农小卡拉28 分钟前
MyBatis-Flex 全面解析与实战教程:轻量高效的 MyBatis 增强方案
java·mybatis
没有bug.的程序员28 分钟前
Spring Boot 与 Sleuth:分布式链路追踪的集成、原理与线上故障排查实战
java·spring boot·分布式·后端·分布式链路追踪·sleuth·线上故障排查
专注VB编程开发20年33 分钟前
无 $ 后缀的变体版函数(Mid、InStr)
java·开发语言
牛马11135 分钟前
flutter Riverpod 中的 overrideWith
android·java·flutter
熊猫钓鱼>_>38 分钟前
深入理解Java堆栈:从原理到面试实战
java·开发语言·面试·职场和发展·面向对象·堆栈·oop
cici1587442 分钟前
基于MATLAB的非正交多址(NOMA)系统协同中继技术提升小区边缘用户性能实现
java·服务器·matlab
bigdata-rookie44 分钟前
Starrocks 数据模型
java·前端·javascript
爱敲代码的憨仔1 小时前
Spring-AOP
java·后端·spring