在Dubbo 里如何手动实现网关聚合功能?

核心是使用RpcContext内置对象,RpcContext 是一个 ThreadLocal 的临时状态记录器,当接收到 RPC 请求,或发起 RPC 请求时,RpcContext 的状态都会变化。比如:A 调 B,B 再调 C,则 B 机器上,在 B 调 C 之前,RpcContext 记录的是 A 调 B 的信息,在 B 调 C 之后,RpcContext 记录的是 B 调 C 的信息。

// 远程调用
xxxService.xxx();
// 本端是否为消费端,这里会返回true
boolean isConsumerSide = RpcContext.getContext().isConsumerSide();
// 获取最后一次调用的提供方IP地址
String serverIP = RpcContext.getContext().getRemoteHost();
// 获取当前服务配置信息,所有配置信息都将转换为URL的参数
String application = RpcContext.getContext().getUrl().getParameter("application");
// 注意:每发起RPC调用,上下文状态会变化
yyyService.yyy();

思路是把聚合服务作为PRC调用方,调用一次服务后,记录服务的ip地址,然后配合配置文件里定义的端口,进行跳转;这种方案的缺点是ip是可以随机的,但是端口需要在配置文件里写死

聚合服务核心代码:

@Controller
@RequestMapping(value = "router")
public class RouterController {

    @Value("${services.ports.user}")
    private String userPort;

    @Value("${services.ports.content}")
    private String contentPort;

    @Reference(version = "${services.versions.user.v1}")
    private UserConsumerService userConsumerService;

    @Reference(version = "${services.versions.content.v1}")
    private ContentConsumerService contentConsumerService;

    @RequestMapping(value = "user", method = RequestMethod.GET)
    public String user(String path) {
        // 远程调用
        userConsumerService.info();
        return getRequest(userPort,path);
    }

    @RequestMapping(value = "content", method = RequestMethod.GET)
    public String content(String path) {
        // 远程调用
        contentConsumerService.info();
        return getRequest(contentPort,path);
    }

    /**
     * 获取请求地址
     * @param port
     * @param path
     * @return
     */
    public String getRequest(String port,String path) {

        // 本端是否为消费端,这里会返回true
        boolean isConsumerSide = RpcContext.getContext().isConsumerSide();

        if (isConsumerSide) {
            // 获取最后一次调用的提供方IP地址
            String serverIP = RpcContext.getContext().getRemoteHost();
            String format = String.format("redirect:http://%s:%s%s", serverIP, port, path);
            return format;
        }
        return null;
    }
}
原文地址:https://www.cnblogs.com/zhenhunfan2/p/13722952.html