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

}
相关推荐
ldj2020几秒前
SpringBoot为什么使用new RuntimeException() 来获取调用栈?
java·spring boot·后端
超龄超能程序猿1 分钟前
Spring 应用中 Swagger 2.0 迁移 OpenAPI 3.0 详解:配置、注解与实践
java·spring boot·后端·spring·spring cloud
风象南13 分钟前
SpringBoot配置属性热更新的轻量级实现
java·spring boot·后端
洛阳泰山14 分钟前
Spring Boot 整合 Nacos 实战教程:服务注册发现与配置中心详解
java·spring boot·后端·nacos
Y40900114 分钟前
C语言转Java语言,相同与相异之处
java·c语言·开发语言·笔记
YuTaoShao15 分钟前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
布朗克16815 分钟前
java常见的jvm内存分析工具
java·jvm·数据库
都叫我大帅哥1 小时前
深入浅出 Resilience4j:Java 微服务的“免疫系统”实战指南
java·spring cloud
Cao_Shixin攻城狮3 小时前
Flutter运行Android项目时显示java版本不兼容(Unsupported class file major version 65)的处理
android·java·flutter
Dcs6 小时前
还在用 Arrays.hashCode?Java 自己也能写出更快的版本!
java