基于Spring Boot Starter的小型RPC框架。编写这个RPC框架并不是为了重复造轮子,而是出于学习的目的,通过手写一款RPC框架来达到知识的学习和应用目的。简易的
RPC
框架(danran-rpc
),底层使用Netty
进行网络通信,使用Zookeeper
为注册中心。该项目可以Maven打包直接加入其他项目运行。另外一个仓库:
https://gitee.com/lengdanran/danran-rpc-debug
https://github.com/lengdanran/danran-rpc-debug
为该项目的整合调试仓库,在里面可调试
danran-rpc
的源码
https://gitee.com/lengdanran/danran-rpc.git
https://github.com/lengdanran/danran-rpc.git
从以上的git仓库地址clone代码到本地,然后进入到项目pom目录中,执行maven安装命令:
mvn clean install
引入打包安装好的maven依赖,因为该RPC框架内部使用了和Springboot本身冲突的日志框架,引入依赖时,最好将danran-rpc
的日志依赖移除,避免程序无法启动。
<dependency>
<groupId>danran.rpc</groupId>
<artifactId>danran-rpc-spring-boot-starter</artifactId>
<version>1.0.1</version>
<!--排除日志冲突-->
<exclusions>
<exclusion>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</exclusion>
</exclusions>
</dependency>
在项目的application.properties
添加如下配置
danran.rpc.register-address=121.4.195.203:2181 # zk的地址
danran.rpc.protocol=danran
danran.rpc.server-port=6666
package provider.service;
import common.api.BookService;
import common.entity.Book;
import danran.rpc.annotation.RPCService;
import org.springframework.beans.factory.annotation.Autowired;
import provider.mapper.BookMapper;
import java.util.List;
/**
* @Classname BookServiceImpl
* @Description TODO
* @Date 2021/8/24 15:50
* @Created by ASUS
*/
@RPCService
public class BookServiceImpl implements BookService {
@Autowired
private BookMapper bookMapper;
/**
* @return 所有的书籍信息
*/
@Override
public List<Book> getAllBooks() {
return bookMapper.getAllBooks();
}
}
在具体的服务实现类上添加@RPCService
注解,即可将该类作为服务提供者注册到zookeeper
中,消费端可以发现该服务,添加该注解之后,将会作为Spring的Component注入到Spring的容器中。(不再需要添加@Component注解)
package consumer.controller;
import common.api.BookService;
import common.entity.Book;
import danran.rpc.annotation.InjectService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* @Classname ConsumerController
* @Description TODO
* @Date 2021/8/24 19:04
* @Created by ASUS
*/
@RestController
@RequestMapping("/consumer")
public class ConsumerController {
@InjectService
private BookService bookService;
@GetMapping("/get_all_books")
public List<Book> getAllBooks() {
return bookService.getAllBooks();
}
}
使用@InjectService
注解,可以启动服务发现,然后自动注入远程服务的代理对象。
启动两个Springboot的web服务,provider提供查询数据库的具体实现,consumer远程调用该服务。
启动postman接口调试工具,访问服务接口:
接口成功返回数据,查看程序日志:
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。