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

}
相关推荐
wuqingshun3141591 分钟前
说说mybatis的缓存机制
java·缓存·mybatis
空中海27 分钟前
Kubernetes 生产实践、可观测性与扩展入门
java·贪心算法·kubernetes
Devin~Y43 分钟前
大厂Java面试实录:Spring Boot/Cloud、Kafka、Redis、K8s 与 Spring AI(RAG/Agent)三轮连环问
java·spring boot·redis·mysql·spring cloud·kafka·kubernetes
bLEd RING1 小时前
SpringBoot3.3.0集成Knife4j4.5.0实战
java
小松加哲1 小时前
Spring MVC 核心原理全解析
java·spring·mvc
Ulyanov1 小时前
《PySide6 GUI开发指南:QML核心与实践》 第二篇:QML语法精要——构建声明式UI的基础
java·开发语言·javascript·python·ui·gui·雷达电子对抗系统仿真
码界筑梦坊2 小时前
357-基于Java的大型商场应急预案管理系统
java·开发语言·毕业设计·知识分享
云烟成雨TD2 小时前
Spring AI Alibaba 1.x 系列【31】集成 Studio 模块实现可视化 Agent 调试
java·人工智能·spring
014-code2 小时前
Spring Data JPA 实战指南
java·spring
安小牛2 小时前
Android 开发汉字转带声调的拼音
android·java·学习·android studio