一、概述
1.开发任务:基于spring-date-redis的Redis的操作实例。
2.开发周期: 4天。
3.成果: 开发了生产者/消费者模式的消息队列。
二、实施方案
1.使用SpringMVC,Spring-data-redis框架。
2.工程结构如下:
三、技术原理
1.spring-data-redis的使用流程
2.RedisTemplate常用API
1.opsForValue() 这个连接内可以做多个操作,不针对某个key
2.boundValue() 针对这个key的多个操作
3.消息生产者:
1 //重写run方法
2 @Override3 public voidrun() {4 try{5 this.product(); //生产消息方法
6 } catch(Exception e) {7 e.printStackTrace();8 }9 }10
11 //PostConstruct注解可以在Spring容器启动后自动运行该方法
12 @PostConstruct13 public voidinit() {14 this.start(); //启动生产者线程
15 }16
17 //生产消息
18 public void product() throwsInterruptedException {19 int i = 0;20
21 Random random = newRandom();22 int max = 6000;23 int min = 4000;24 int dms = random.nextInt(max-min+1) + min; //线程睡眠随机数
25
26 redisTemplate.delete("msg"); //清除遗留数据
27
28 while(true) {29 messageEntity.setMessage("{消息"+i+"}");30 redisTemplate.opsForList().leftPush("msg",messageEntity); //消息入队列
31 System.out.println("生产了:"+messageEntity.getMessage());32
33 this.sleep(dms);34 i++;35 }36
37 }
4.消费者1号(2号代码相似):
//重写run方法
@Overridepublic voidrun() {try{this.consume();
}catch(Exception e) {
e.printStackTrace();
}
}//PostConstruct注解可以在Spring容器启动后自动运行该方法
@PostConstructpublic voidinit() {this.start(); //启动消费者线程
}public void consume() throwsInterruptedException {
Random random= newRandom();int max = 15000;int min = 8000;int dms = random.nextInt(max-min+1) + min; //线程睡眠随机数
while(true) {if((messageEntity = redisTemplate.opsForList().rightPop("msg")) !=null ) { //消息出队列,检查是否为空
System.out.print("消费者1号消费:");
System.out.println(messageEntity.getMessage());
}else{
System.out.println("消费者1号: 队列里没消息了");
}this.sleep(dms);
}
}
5.消息实体类:
public class MessageEntity implementsSerializable {privateString id;privateString message;publicString getId() {returnid;
}public voidsetId(String id) {this.id =id;
}publicString getMessage() {returnmessage;
}public voidsetMessage(String name) {this.message =name;
}
}
四、成果展示
1.运行效果:
五、总结
Redis性能不错, 本次只是简单用了操作API和消息队列的实现, 还没有体会到更强大之处,期待以后能用到其强大的功能。
源码: