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

}
相关推荐
葡萄成熟时 !18 小时前
正则表达式
java·正则表达式
无心水18 小时前
微服务架构下Dubbo线程池选择与配置指南:提升系统性能与稳定性
java·开发语言·微服务·云原生·架构·java-ee·dubbo
Chan1618 小时前
《Java并发编程的艺术》| 并发关键字与 JMM 核心规则
java·开发语言·数据库·spring boot·java-ee·intellij-idea·juc
期待のcode18 小时前
线程睡眠sleep方法
java·开发语言
汤姆yu18 小时前
基于springboot的植物花卉销售管理系统
java·spring boot·后端
不想写bug呀18 小时前
RabbitMQ相关问题(1)
java·rabbitmq
海南java第二人18 小时前
Spring Boot Starters深度解析:简化依赖管理的核心利器
java·spring boot·后端
captain37618 小时前
Java-链表
java·开发语言·链表
tqs_1234518 小时前
跳出多层循环的方式
java·开发语言
东方轧线19 小时前
突破锁竞争的性能枷锁:深度剖析 C++ 内存模型与无锁编程在超大规模并行 AI 系统中的极致应用实践
java·c++·人工智能