抽象公共代码块,使用Dubbo RPC框架实现子系统间的高性能调用
- 为什么要抽象公共代码块
因为对于同一个模块,如公共的User等在不同的模块都需要重复写,我们程序员最忌讳的就是重复的写一个东西,可以将多个模块中重复的代码抽象成公共代码块,然后通过maven引入
- 怎么抽象成公共代码块
在我的项目中,我将模型层和业务层抽象成了公共模块在common项目中
项目结构图
然后使用maven的install指令就可以在需要的项目中的pom.xml中引入
- 为什么需要Dubbo RPC
在我们使用的网关项目中没有操作数据库的包,我们需要操作数据库的时候难道又要使用CV大法吗?
有没有一种能够直接调用别的项目中的方法的操作?
我们需要使用RPC(远程过程调用)像调用本地方法一样调用远程方法
RPC调用模型
- 怎么实现
选用nacos作为注册中心
通过官方文档,快速下载并启动注册中心
在服务的提供方和消费方引入依赖
<!-- https://mvnrepository.com/artifact/org.apache.dubbo/dubbo -->
<dependency>
<groupId>org.apache.dubbo</groupId>
<artifactId>dubbo</artifactId>
<version>3.0.9</version>
</dependency>
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>2.1.0</version>
</dependency>
Provider
配置文件application.yml
dubbo:
# 应用名
application:
name: dubbo-springboot-demo-provider
# 协议信息
protocol:
name: dubbo
port: -1
# 注册中心地址
registry:
id: nacos-registry
address: nacos://localhost:8848
在主启动类上加入@EnableDubbo注解
@SpringBootApplication(exclude = {RedisAutoConfiguration.class})
@MapperScan("com.xc.project.mapper")
@EnableScheduling
@EnableAspectJAutoProxy(proxyTargetClass = true, exposeProxy = true)
@EnableDubbo
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
对需要提供给注册中心的类加上注解比如接口统计次数加一的方法
@DubboService
public class InnerUserInterfaceInfoServiceImpl implements InnerUserInterfaceInfoService {
@Resource
private UserInterfaceInfoService userInterfaceInfoService;
@Override
public boolean invokeCount(long interfaceInfoId, long userId) {
return userInterfaceInfoService.invokeCount(interfaceInfoId, userId);
}
@Override
public boolean leftInvokeCount(long interfaceInfoId, long userId) {
return userInterfaceInfoService.leftInvokeCount(interfaceInfoId, userId);
}
}
Consumer
配置文件application.yml
dubbo:
# 应用名
application:
name: dubbo-springboot-demo-consumer
# 协议信息
protocol:
name: dubbo
port: -1
# 注册中心地址
registry:
id: nacos-registry
address: nacos://localhost:8848
在网关项目中的主启动类加上相应的注解
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class})
@EnableDubbo
public class XcapiGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(XcapiGatewayApplication.class, args);
}
}
在网关的拦截器中将需要调用的接口通过dubbo注入
@DubboReference
private InnerUserService innerUserService;
@DubboReference
private InnerInterfaceInfoService innerInterfaceInfoService;
@DubboReference
private InnerUserInterfaceInfoService innerUserInterfaceInfoService;
具体的实现类在provider中,这里就可以来实现远程调用