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

}
相关推荐
阿维的博客日记5 小时前
MultipartFile 是不是表示仅仅是一个分片?
java·后端·spring·multipartfile
程序员无隅5 小时前
Coding Agent 为什么压缩上下文后还能继续工作?上下文模块设计拆解
java·开发语言·数据库
Python+995 小时前
Java 枚举类(Enum)详解:从基础到高级应用
java·开发语言·python
二炮手亮子5 小时前
浅记java线程池
java·开发语言
一路向北North5 小时前
Spring Security OAuth2.0(23):分布式系统授权-转发明文给微服务
java·spring·微服务
专注_每天进步一点点6 小时前
SLB(绑定弹性公网ip)-gateway-业务pod,gateway上出现reset by peer,业务pod上没有reset by peer
服务器·tcp/ip·gateway
爱吃牛肉的大老虎7 小时前
rust基础之环境搭建
java·开发语言·rust
tellmewhoisi8 小时前
多版本共用redis的token有效期校验(过期重新登录)
java·redis·缓存
疯狂打码的少年8 小时前
【软件工程】结构化设计:模块独立性与耦合内聚
java·开发语言·笔记·软件工程
乐观的Terry8 小时前
3、数据库设计与领域实体
java·数据库·spring boot·spring cloud·ai编程