dubbo转http方式调用

news/2025/2/26 12:44:02

业务背景:在当前项目下,所有前端请求均通过外层网关转发到后端这边的dubbo服务,现计划去掉网关层,由前端直接http调用后端dubbo

解决方案:在前端调用方式不变的前提下,后端服务新建controller层(原后端服务无任何controller),做统一请求兼容转发

package cn.***********.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.ApplicationConfig;
import org.apache.dubbo.config.ReferenceConfig;
import org.apache.dubbo.config.RegistryConfig;
import org.apache.dubbo.config.utils.ReferenceConfigCache;
import org.apache.dubbo.rpc.service.GenericService;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.List;
import java.util.Map;

/**
 * Dubbo调用controller
 * @Version:1.0
 * @Desc
 */
@Slf4j
@RestController
@RequestMapping("/api/test/")
public class GenericController {

    @PostMapping("/{service}/{method}")
    public Object invoke(HttpServletRequest request,
                         @PathVariable("service") String service,
                         @PathVariable("method") String method) {
        Object result;
        try {
            GenericService tarService = this.getTargetService(service);
            if(tarService ==  null){
                throw new RuntimeException("获取service失败");
            }
            // 1.解析传入参数
            String paramStr = this.parseInputStream(request);
            // 获取目标接口的 Class 对象
            Class<?> serviceInterface = Class.forName(service);

            // 获取方法的参数类型
            String[] parameterTypes = this.getMethodParameterTypes(serviceInterface, method);

            // 将 JSON 字符串转换为目标参数值
            Object[] parameters = this.convertParameters(paramStr, parameterTypes);

            // 调用方法
            result = tarService.$invoke(method, parameterTypes, parameters);

        } catch (Exception e) {
            log.error("服务调用失败, service={},method={}",service, method, e);
            throw new ErrorCodeException("000000", "系统异常,请稍后重试");
        }
        return result;
    }

    /**
     * 获取请求文本
     *
     * @return
     */
    public String parseInputStream(HttpServletRequest request) {
        try {
            ServletInputStream inputStream = request.getInputStream();
            StringBuilder content = new StringBuilder();
            int size = request.getContentLength();
            byte[] b = new byte[size];
            int lens;
            while ((lens = inputStream.read(b)) > 0) {
                content.append(new String(b, 0, lens, "utf-8"));
            }
            return content.toString();
        } catch (IOException e) {
            log.error("请求报文解析失败", e);
            throw new RuntimeException("请求报文解析异常");
        }
    }

    /**
     * 获取目标dubbo服务
     * @params [service]
     * @return org.apache.dubbo.rpc.service.GenericService
     * @desc
     */
    private GenericService getTargetService(String service){
        // 应用信息
        ApplicationConfig application = SpringBeanUtils.getBean(ApplicationConfig.class);
        // 注册中心发现
        RegistryConfig registry = SpringBeanUtils.getBean(RegistryConfig.class);
        // 引用远程服务
        ReferenceConfig<GenericService> reference = new ReferenceConfig<>();
        reference.setApplication(application);
        reference.setRegistry(registry);
        reference.setProtocol("dubbo");
        reference.setInterface(service);
        reference.setTimeout(10000);
        reference.setRetries(0);
        // 声明为泛化接口
        reference.setGeneric(true);
        ReferenceConfigCache cache = ReferenceConfigCache.getCache();
        GenericService genericService = cache.get(reference);
        if(genericService == null){
            genericService = reference.get();
        }
        return genericService;
    }

    /**
     * 将 JSON 字符串转换为目标参数值
     * @params [paramStr, parameterTypes]
     * @return java.lang.Object[]
     * @author wu.zeng
     * @date 2025/2/21 13:44
     * @desc
     */
    private Object[] convertParameters(String paramStr, String[] parameterTypes) {
        Object[] parameters = new Object[parameterTypes.length];
        for (int i = 0; i < parameterTypes.length; i++) {
            String paramType = parameterTypes[i];
            switch (paramType) {
                case "java.lang.String":
                    parameters[i] = paramStr;
                    break;
                case "java.lang.Integer":
                    parameters[i] = Integer.parseInt(paramStr);
                    break;
                case "java.lang.Long":
                    parameters[i] = Long.parseLong(paramStr);
                    break;
                case "java.util.Map":
                    parameters[i] = JSON.parseObject(paramStr, new TypeReference<Map<String, Object>>() {});
                    break;
                case "java.util.List":
                    parameters[i] = JSON.parseObject(paramStr, new TypeReference<List<Object>>() {});
                    break;
                default:
                    // 如果是自定义类型,使用反射或 JSON 反序列化
                    try {
                        Class<?> clazz = Class.forName(paramType);
                        parameters[i] = JSON.parseObject(paramStr, clazz);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException("不支持的类型: " + paramType, e);
                    }
            }
        }
        return parameters;
    }

    /*
     * 获取目标方法的参数类型
     * @params [serviceInterface, methodName]
     * @return java.lang.String[]
     * @desc
     */
    public String[] getMethodParameterTypes(Class<?> serviceInterface, String methodName) {
        for (Method method : serviceInterface.getMethods()) {
            // 由于不支持重载,因此这里可以根据 methodName 来匹配方法
            if (method.getName().equals(methodName)) {
                Parameter[] parameters = method.getParameters();
                String[] parameterTypes = new String[parameters.length];
                for (int i = 0; i < parameters.length; i++) {
                    parameterTypes[i] = parameters[i].getType().getName();
                }
                return parameterTypes;
            }
        }
        throw new RuntimeException("方法未找到: " + methodName);
    }
}


http://www.niftyadmin.cn/n/5868710.html

相关文章

安装TortoiseGit时,显示需要安装驱动?!

安装TortoiseGit时&#xff0c;显示需要安装驱动&#xff1f; 原因分析&#xff1a; 出现上述情况&#xff0c;单纯是被捆绑了&#xff0c;TortoiseGit是不需要任何插件 解决方案&#xff1a; 在电脑上选择应用Windows安装程序

VMware中的linux常用指令

常用 Linux 基础命令 文件与目录操作 ls&#xff1a;查看当前目录的文件和子目录&#xff0c;ls -a显示所有文件&#xff0c;包括隐藏文件。cd&#xff1a;切换目录&#xff0c;如 **cd ~** 切换到个人家目录。pwd&#xff1a;查看当前目录。mkdir&#xff1a;创建文件夹&#…

DeepSeek在金融银行的应用方案

1. 引言 随着金融科技的迅猛发展&#xff0c;传统金融银行业面临着前所未有的挑战与机遇。数字化转型已成为金融银行业提升效率、优化客户体验、增强竞争力的必由之路。在这一背景下&#xff0c;DeepSeek作为一款先进的智能解决方案&#xff0c;凭借其强大的数据分析能力、智能…

python-leetcode-字符串解码

394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; class Solution:def decodeString(self, s: str) -> str:stack []num 0curr_str ""for char in s:if char.isdigit():num num * 10 int(char)elif char [:stack.append((curr_str, num))curr_str, …

Python驱动的餐饮企业智能数据分析:从数据清洗到可视化决策全流程实战

文章目录 Python驱动的餐饮企业智能数据分析:从数据清洗到可视化决策全流程实战引言一、案例背景1.1 需求分析1.2 数据准备1.2.1 模拟数据生成代码二、数据处理全流程2.1 数据清洗2.1.1 缺失值处理2.1.2 异常值检测2.2 核心指标计算2.2.1 营业额分析2.2.2 门店表现评估2.2.3 菜…

Docker 部署 Graylog 日志管理系统

Docker 部署 Graylog 日志管理系统 前言一、准备工作二、Docker Compose 配置三、启动 Graylog 服务四、访问 Graylog Web 界面总结 前言 Graylog 是一个开源的日志管理平台&#xff0c;专为实时日志收集、分析和可视化设计。它支持强大的搜索功能&#xff0c;并且与 Elastics…

智能升级、安全加倍,遨游防爆对讲机拉起通信安防线

在充斥着爆炸性气体和易燃物质的危险作业环境中&#xff0c;通信设备的选择关乎生命安全。一旦通信设备引发电火花&#xff0c;其后果将不堪设想。因此&#xff0c;专为防范易燃易爆环境而设计的防爆对讲机&#xff0c;凭借其独特的防爆技术和设计&#xff0c;成为了这些高风险…

【SQLI】CTF 无回显SQL盲注解题方法

CTF 无回显SQL盲注解题方法 1. 确认注入点与数据库类型2. 构造条件判断提取数据3. 自动化利用脚本4. 外带数据&#xff08;OOB Exfiltration&#xff09;5. 绕过过滤与WAF6. 关键数据提取路径7. 工具推荐总结 在CTF中解决无任何回显的SQL注入题目&#xff0c;通常需要依赖盲注技…