前言碎语
本篇博文承接上一篇文章《java基于RabbitMQ+Hessian+spring实现RPC远程调用框架》,今天来写写预告说的怎么使用redis来玩RPC,关于redis是什么怎么在Windows上安装环境等内容本篇就不谈了,不懂的可以先谷歌或百度下,好了,下面直接上代码,本项目构建于spring boot+maven+redisson之上。
第一步,使用IDE工具上的Spring Initializr创建spring boot工程,并引入redisson依赖
<dependency> <groupId>org.redisson</groupId> <artifactId>redisson</artifactId> <version>3.5.4</version> </dependency>
第二步,集成redisson,使用默认配置,不显示配置redis地址,默认会链接本地127.0.0.1:6379的redis
@SpringBootApplicationpublic class RedisrpcApplication {
public static void main(String[] args) {
SpringApplication.run(RedisrpcApplication.class, args);
} /**
* 集成redisson
* @return
* @throws IOException
*/
@Bean(destroyMethod="shutdown")
RedissonClient redisson() throws IOException { return Redisson.create();
}
}第三步,声明客户端接口,这里声明了一个sayHello的服务接口
/**
* Created by kl on 2017/10/29.
*/public interface SayHelloService {
String sayHello(String name);
}第四步,服务的实现,在服务方实现客户端提供的接口
/**
* Created by kl on 2017/10/29.
*/public class SayHelloServiceImpl implements SayHelloService {
@Override
public String sayHello(String name) {
System.err.println("你好:"+name); return name+":谢谢你,收到你的问候了";
}
}第五步,服务端注册sayHello的服务,客户端调用服务,分别使用两个测试用例来模拟服务的注册和调用
@RunWith(SpringRunner.class)@SpringBootTestpublic class RedisrpcApplicationTests {
@Autowired
RedissonClient redissonClient; /**
* sayHello服务方,注册服务
*/
@Test
public void sayHelloServer() throws IOException {
RRemoteService remoteService=redissonClient.getRemoteService();
remoteService.register(SayHelloService.class,new SayHelloServiceImpl());
System.in.read();
} /**
* sayHello客户端,调用服务
*/
@Test
public void sayHelloClient(){
RRemoteService remoteService=redissonClient.getRemoteService();
SayHelloService helloService=remoteService.get(SayHelloService.class);
String result=helloService.sayHello("小陈博主");
System.err.println("远程服务返回结果:"+result);
}
}第六步,哈哈,迫不及待的想调用下吧,我的测试结果如下
文末彩蛋
我的独立博客地址:http://www.kailing.pub/,大家可以收藏下我的博客地址,我的博客有很多在线的java编程开发秘籍,哈哈
我的开源项目:https://www.oschina.net/p/springboot-mqrpc
我的coding仓库:https://coding.net/u/kailingchen
头条网友们好,走过路过不要错过,没关注可以关注一波,后面还会陆续发布更多java等web领域开发相关的精彩内容,本文源码工程后面会整理上传到我的coding仓库
