实现RPC接口的demo记录

1.Thrift RPC 接口实现 Demo

java 复制代码
@Service
public class DemoServiceImpl implements DemoService.Iface {

    private static final Logger logger = LoggerFactory.getLogger(DemoServiceImpl.class);

    @Override
    public String sayHello(Context context, String msg) throws TException {
        logger.info("接收到 RPC 请求, msg: {}", msg);
        return "Hello " + msg;
    }
}

2.Thrift RPC 配置 Demo

java 复制代码
@Configuration
public class DemoThriftConfiguration {

    @Value("${rpc.server.port:9090}")
    private int port;

    /**
     * 定义 Thrift Server
     */
    @Bean
    public ServiceBuilder<DemoService.Iface> demoServer(DemoServiceImpl serviceImpl) {
        return ServiceBuilder.fromInstance(DemoService.Iface.class, port, serviceImpl);
    }


    /**
     * 定义 Thrift Client
     */
    @Bean
    public DemoService.Iface demoClient() {
        return ClientBuilder.create(DemoService.Iface.class, "excover")
                .withTimeout(2000, TimeUnit.MILLISECONDS)
                // 直连地址,仅用于本地测试;这里请求服务自己
                .withDirectHost(HostAndPort.fromParts("127.0.0.1", port))
                .buildStub();
    }
}
复制代码
3.Thrift RPC Client 调用 Demo
java 复制代码
@RestController
@RequestMapping("/rpc")
public class DemoThriftController {

    private static final Logger logger = LoggerFactory.getLogger(DemoThriftController.class);

    @Resource
    private DemoService.Iface demoClient;

    /**
     * curl http://127.0.0.1:8080/rpc/sayHello\?msg=demo
     */
    @GetMapping("/sayHello")
    public String sayHello(String msg) {
        try {
            return demoClient.sayHello(ContextHelper.getContext(), msg);
        } catch (TException e) {
            logger.error("RPC 请求失败: {}", e.getMessage(), e);
            return "error";
        }
    }
}
相关推荐
157092511346 小时前
Android进阶之光:HTTP协议原理深度解析
android·网络协议·http
虹科网络安全8 小时前
Redis 安全公告:CVE-2026-81934 TLS 处理漏洞及修复建议
网络·人工智能·网络安全
小程序设计9 小时前
某师范学院网络规划与设计
网络·安全
可爱系程序猿10 小时前
WSD 打印机时好时坏:从发现服务、地址变化到 Standard TCP/IP 端口的迁移记录
网络·网络协议·tcp/ip·程序人生·电脑
蓝速科技11 小时前
便民服务大厅 AI 数字人一体机场景适配与落地指南丨蓝速科技
大数据·网络·数据结构·人工智能·自然语言处理·数据分析·运维开发
济南凡维12 小时前
CODESOFT中如何将标签保存为PDF文件
网络·人工智能·打印机·codesoft
德迅云安全杨德俊12 小时前
高防IP:构建“防护-加速-管控”三位一体的全链路安全体系
网络·安全·ddos
猫哥随身wifi13 小时前
随身WiFi 怎么选?2026 主流品牌随身 WiFi 对比与选购避坑参考
网络·人工智能·5g·智能手机
en.en..13 小时前
TCP套接字编程 完整流程解析(服务端 + 客户端)
网络
Quanqiucard13 小时前
“十五五”数字乡村建设提速,平安乡村监控物联网卡怎么选才稳定
网络·物联网