目录
一 RPC 是什么
RPC,Remote Procedure Call,顾名思义就是远程过程调用,一般都有跨语言支持。大规模分布式应用中普遍使用 RPC 来做内部服务、模块之间的数据通信,有助于解耦服务、系统的垂直拆分,使得系统可扩展性更强。
RPC 分为客户端(服务调用方)和服务端(服务提供方),都运行在自己的 JVM 中。客户端只需要引入要使用的接口,接口的实现和运行都在服务端。RPC 主要依赖的技术包括序列化、反序列化和数据传输协议,这是一种定义与实现相分离的设计,如图所示:
二 Hessian 是什么
Hessian 是一个基于 HTTP 协议的 RPC 方案,自己实现序列化,负载均衡和容错需要依赖于 Web 容器/服务,其实现方式如图所示:
三 服务端实现
3.1 创建 Hessian 接口
public interface UserRpcService {
User getById(long id);
}
3.2 创建 Hessian 接口的实现类
@Service
public class UserRpcServiceImpl implements UserRpcService {
@Override
public User getById(long id) {
//业务逻辑
}
}
3.3 配置 Hessian 服务端接口服务
@EnableWebMvc
@SpringBootConfiguration
public class HessianService {
@Resource
private UserRpcService userRpcService;
@Bean(name = "/rpc/userRpcService")
public HessianServiceExporter hessianServiceExporter(){
HessianServiceExporter hessianServiceExporter = new HessianServiceExporter();
hessianServiceExporter.setServiceInterface(UserRpcService.class);
hessianServiceExporter.setService(userRpcService);
return hessianServiceExporter;
}
}
服务端生成 jar 包给到客户端。
四 客户端实现
4.1 客户端引入 jar 包依赖,客户端实现。
@Configuration
public class HessainClient {
@Value("${userRpcService.host}")
private String userRpcServiceHost;
@Value("${userRpcService.timeout.connect}")
private int connectionTimeOut;
@Value("${userRpcService.timeout.read}")
private int readTimeout;
@Bean
public HessianWithContextProxyFactoryBean userRpcService() {
HessianWithContextProxyFactoryBean hessianWithContextProxyFactoryBean = new HessianWithContextProxyFactoryBean();
hessianWithContextProxyFactoryBean.setServiceUrl(userRpcServiceHost);
hessianWithContextProxyFactoryBean.setServiceInterface(UserRpcService.class);
hessianWithContextProxyFactoryBean.setOverloadEnabled(true);
hessianWithContextProxyFactoryBean.setConnectTimeout(connectionTimeOut);
hessianWithContextProxyFactoryBean.setHessian2(true);
hessianWithContextProxyFactoryBean.setReadTimeout(readTimeout);
return hessianWithContextProxyFactoryBean;
}
}
4.2 客户端调用
@Component
public class UserService {
@Autowired
UserRpcService userRpcService;
public User getById(long id) {
return userRpcService.getById(id);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/9596.html