一、概述
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 @Override 3 public void run() { 4 try { 5 this.product(); //生產消息方法 6 } catch (Exception e) { 7 e.printStackTrace(); 8 } 9 } 10 11 //PostConstruct注解可以在Spring容器啟動后自動運行該方法 12 @PostConstruct 13 public void init() { 14 this.start(); //啟動生產者線程 15 } 16 17 //生產消息 18 public void product() throws InterruptedException { 19 int i = 0; 20 21 Random random = new Random(); 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方法 @Override public void run() { try { this.consume(); } catch (Exception e) { e.printStackTrace(); } } //PostConstruct注解可以在Spring容器啟動后自動運行該方法 @PostConstruct public void init() { this.start(); //啟動消費者線程 } public void consume() throws InterruptedException { Random random = new Random(); 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 implements Serializable { private String id; private String message; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getMessage() { return message; } public void setMessage(String name) { this.message = name; } }
四、成果展示
1.運行效果:
五、總結
Redis性能不錯, 本次只是簡單用了操作API和消息隊列的實現, 還沒有體會到更強大之處,期待以后能用到其強大的功能。
源碼: