实现RPC接口的demo记录
1.Thrift RPC 接口实现 Demo
@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
@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
@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";
}
}
}