实现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";
        }
    }
}
相关推荐
CiLerLinux3 小时前
第四十九章 ESP32S3 WiFi 路由实验
网络·人工智能·单片机·嵌入式硬件
摩羯座-185690305945 小时前
爬坑 10 年!京东店铺全量商品接口实战开发:从分页优化、SKU 关联到数据完整性闭环
linux·网络·数据库·windows·爬虫·python
YoungLime6 小时前
DVWA靶场之十三:CSP 绕过(Content Security Policy (CSP) Bypass)
网络·安全·web安全
2301_772093567 小时前
tuchuang_后端_前端_注册登录
数据库·后端·网络协议·mysql·wireshark
芝士小宇7 小时前
tcp 服务器的设计思路
服务器·网络·tcp/ip
智能化咨询7 小时前
【深度学习计算机视觉】10:转置卷积实战进阶——破解棋盘效应与工业级应用
网络
cililin8 小时前
第4章 文件管理
linux·服务器·网络·操作系统·unix
驰羽9 小时前
C++网络编程(三)TCP通信流程
服务器·网络·tcp/ip
shylyly_10 小时前
Linux-> TCP 编程1
linux·网络·tcp/ip·echo·tcp编程
夏日漱石_10 小时前
tcp 服务器的设计思路
服务器·网络·tcp/ip