謝謝參考:https://blog.csdn.net/CNZYYH/article/details/85696674
一般來說,消息隊列有兩種場景,一種是發佈者訂閱者模式,一種是生產者消費者模式。利用redis這兩種場景的消息隊列都能夠實現。
定義:
- 生產者消費者模式 :生產者生產消息放到隊列裏,多個消費者同時監聽隊列,誰先搶到消息誰就會從隊列中取走消息;即對於每個消息只能被最多一個消費者擁有。
- 發佈者訂閱者模式:發佈者生產消息放到隊列裏,多個監聽隊列的消費者都會收到同一份消息;即正常情況下每個消費者收到的消息應該都是一樣的。
Redis不僅可作爲緩存服務器,還可用作消息隊列。它的列表類型天生支持用作消息隊列。如下圖所示:
由於Redis的列表是使用雙向鏈表實現的,保存了頭尾節點,所以在列表頭尾兩邊插取元素都是非常快的。
在Redis中,List類型是按照插入順序排序的字符串鏈表。和數據結構中的普通鏈表一樣,我們可以在其頭部(left)和尾部(right)添加新的元素。在插入時,如果該鍵並不存在,Redis將爲該鍵創建一個新的鏈表。與此相反,如果鏈表中所有的元素均被移除,那麼該鍵也將會被從數據庫中刪除。List中可以包含的最大元素數量是4294967295。
從元素插入和刪除的效率視角來看,如果我們是在鏈表的兩頭插入或刪除元素,這將會是非常高效的操作,即使鏈表中已經存儲了百萬條記錄,該操作也可以在常量時間內完成。然而需要說明的是,如果元素插入或刪除操作是作用於鏈表中間,那將會是非常低效的。相信對於有良好數據結構基礎的開發者而言,這一點並不難理解。
Redis List的主要操作爲lpush/lpop/rpush/rpop四種,分別代表從頭部和尾部的push/pop,除此之外List還提供了兩種pop操作的阻塞版本blpop/brpop,用於阻塞獲取一個對象。
Redis通常都被用做一個處理各種後臺工作或消息任務的消息服務器。 一個簡單的隊列模式就是:生產者把消息放入一個列表中,等待消息的消費者用 RPOP 命令(用輪詢方式), 或者用 BRPOP 命令(如果客戶端使用阻塞操作會更好)來得到這個消息。
以下列舉SpringBoot集成redis的JedisCluster和RedisTemplate
引入依賴到pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
application.yml增加redis集羣配置
spring:
redis:
password:
clusters: 10.10.1.238:7000,10.10.1.238:7001,10.10.1.238:7002,10.10.1.238:7003,10.10.1.238:7004,10.10.1.238:7005
RedisConfig配置
package com.example.myframe.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Field;
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
/**redis密碼**/
@Value("${spring.redis.password}")
public String password;
@Value("${spring.redis.clusters}")
public String cluster;
@Bean
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
};
}
public Object getFieldValueByObject (Object object , String targetFieldName) throws Exception {
// 獲取該對象的Class
Class objClass = object.getClass();
// 獲取所有的屬性數組
Field[] fields = objClass.getDeclaredFields();
for (Field field:fields) {
// 屬性名稱
field.setAccessible(true);
String currentFieldName = field.getName();
if(currentFieldName.equals(targetFieldName)){
return field.get(object); // 通過反射拿到該屬性在此對象中的值(也可能是個對象)
}
}
return null;
}
/**
* 通過反射獲取JedisCluster
* @param factory
* @return
*/
@Bean
public JedisCluster redisCluster(RedisConnectionFactory factory){
Object object =null;
try {
object= getFieldValueByObject(factory,"cluster");
} catch (Exception e) {
e.printStackTrace();
}
return (JedisCluster)object;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean(name="factory")
public RedisConnectionFactory factory(RedisClusterConfiguration clusterConfig){
JedisConnectionFactory redisConnectionFactory=new JedisConnectionFactory(clusterConfig);
String redisPassword = password;
redisConnectionFactory.setPassword(redisPassword);
redisConnectionFactory.setPoolConfig(createJedisPoolConfig());
redisConnectionFactory.setTimeout(30000);
redisConnectionFactory.setUsePool(true);
return redisConnectionFactory;
}
@Bean(name="clusterConfig")
public RedisClusterConfiguration clusterConfig(){
RedisClusterConfiguration config = new RedisClusterConfiguration();
String[] nodes = cluster.split(",");
for(String node : nodes){
String[] host = node.split(":");
RedisNode redis = new RedisNode(host[0], Integer.parseInt(host[1]));
config.addClusterNode(redis);
}
return config;
}
public JedisPoolConfig createJedisPoolConfig(){
JedisPoolConfig config = new JedisPoolConfig();
//連接耗盡時是否阻塞, false報異常,ture阻塞直到超時, 默認true
config.setBlockWhenExhausted(false);
//設置的逐出策略類名, 默認DefaultEvictionPolicy(當連接超過最大空閒時間,或連接數超過最大空閒連接數)
config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
//是否啓用pool的jmx管理功能, 默認true
config.setJmxEnabled(true);
//MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默 認爲"pool", JMX不熟,具體不知道是幹啥的...默認就好.
config.setJmxNamePrefix("pool");
//是否啓用後進先出, 默認true
config.setLifo(true);
//最大空閒連接數, 默認8個
config.setMaxIdle(2000);
//最大連接數, 默認8個
config.setMaxTotal(5000);
//獲取連接時的最大等待毫秒數(如果設置爲阻塞時BlockWhenExhausted),如果超時就拋異常, 小於零:阻塞不確定的時間, 默認-1
config.setMaxWaitMillis(10000);
//逐出連接的最小空閒時間 默認1800000毫秒(30分鐘)
config.setMinEvictableIdleTimeMillis(1800000);
//最小空閒連接數, 默認0
config.setMinIdle(0);
//每次逐出檢查時 逐出的最大數目 如果爲負數就是 : 1/abs(n), 默認3
config.setNumTestsPerEvictionRun(3);
//對象空閒多久後逐出, 當空閒時間>該值 且 空閒連接>最大空閒數 時直接逐出,不再根據MinEvictableIdleTimeMillis判斷 (默認逐出策略)
config.setSoftMinEvictableIdleTimeMillis(1800000);
//在獲取連接的時候檢查有效性, 默認false
config.setTestOnBorrow(false);
//在空閒時檢查有效性, 默認false
config.setTestWhileIdle(false);
//逐出掃描的時間間隔(毫秒) 如果爲負數,則不運行逐出線程, 默認-1
config.setTimeBetweenEvictionRunsMillis(-1);
return config;
}
}
RedisService.java輔助類
package com.example.myframe.redis.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Service;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Service("redisService")
public class RedisService {
@Autowired
private RedisTemplate redisTemplate;
/**
* 寫入緩存
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 寫入緩存設置時效時間
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量刪除對應的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量刪除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0){
redisTemplate.delete(keys);
}
}
/**
* 刪除對應的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判斷緩存中是否有對應的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 讀取緩存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}
/**
* 哈希 獲取哈希的key集合
* @param key
* @return
*/
public Set<Object> hmKeys(String key){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.keys(key);
}
/**
* 哈希 刪除哈希的key
* @param key
* @param hashKey
*/
public void hmDelete(String key,String hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.delete(key, hashKey);
}
/**
* 哈希獲取數據
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key,hashKey);
}
/**
* 獲取所有key值
* @param key
* @return
*/
public Set<Object> hmKeySet(String key){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.keys(key);
}
/**
* 獲取所有key值
* @param key
* @return
*/
public void hmRemove(String key, Object hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.delete(key, hashKey);
}
/**
* 列表添加
* @param k
* @param v
*/
public void lPush(String k,Object v){
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k,v);
}
/**
* 列表獲取
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1){
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k,l,l1);
}
/**
* 集合添加
* @param key
* @param value
*/
public void add(String key,Object value){
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key,value);
}
/**
* 集合獲取
* @param key
* @return
*/
public Set<Object> setMembers(String key){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 集合長度
* @param key
* @return
*/
public Long setSize(String key){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.size(key);
}
/**
* 集合獲取
* @param key
* @param count
* @return
*/
public Set<Object> setMembers(String key, int count){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.distinctRandomMembers(key, count);
}
/**
* 刪除集合數據
* @param key
* @param value
*/
public void remove(String key, Object value){
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.remove(key, value);
}
/**
* 有序集合添加
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key,Object value,double scoure){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key,value,scoure);
}
/**
* 有序集合獲取
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key,double scoure,double scoure1){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
/**
* 消息隊列實現
* @param channel
* @param message
*/
public void convertAndSend(String channel, Object message){
redisTemplate.convertAndSend(channel, message);
}
/**
* 數列添加
* @param key
* @param value
*/
public void addList(String key,Object value){
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(key, value);
}
/**
* 數列獲取
* @param key
* @return
*/
public List<Object> getList(String key){
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(key, 0, list.size(key));
}
/**
* 左彈出數列
* @param key
* @return
*/
public Object popList(String key) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.leftPop(key);
}
public Long increment(String k, Long l) {
return redisTemplate.opsForValue().increment(k, l);
}
}
TestRedisController.java
package com.example.myframe.controller;
import com.example.myframe.redis.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/redis")
public class TestRedisController {
@Autowired
RedisUtil redisUtil;
/**
* 生產者 通過此方法來往redis的list的尾部插入數據
*/
@RequestMapping("/shengchangzhe")
public void shengChangZhe() {
redisUtil.dealShengChangZhe();
}
/**
* 消費者 ,通過此方法往redis的list的頭部獲取數據,直到list沒有數據 阻塞,等到一有數據又繼續獲取
*/
@RequestMapping("/xiaoFeiZhe")
public void xiaoFeiZhe() {
redisUtil.dealXiaoFeiZhe();
}
/**
* 發佈者,發佈信息,監聽器一旦接收到監聽,就進行操作
*/
@RequestMapping("/faBuDingYue")
public void faBuDingYue() {
redisUtil.dealFaBuDingYue();
}
}
package com.example.myframe.redis;
import com.example.myframe.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisCluster;
import java.util.List;
@Component
public class RedisUtil {
@Autowired
JedisCluster jedisCluster;
@Autowired
private RedisService redisService;
/**
* 生產者
*/
public void dealShengChangZhe() {
for (int i = 0; i < 10; i++) {
jedisCluster.rpush("ceshi", "value1_" + i);
}
}
/**
* 消費者
*/
public void dealXiaoFeiZhe() {
while (true) {
//阻塞式brpop,List中無數據時阻塞,參數0表示一直阻塞下去,直到List出現數據
List<String> listingList = jedisCluster.blpop(0, "ceshi");
System.out.println("線程取數據:{}" + listingList.get(1));
}
}
/**
* 發佈訂閱模式
*/
public void dealFaBuDingYue() {
redisService.convertAndSend("dealFaBuDingYue", "我是來發布信息的");
}
}
redis消息隊列監聽信息
package com.example.myframe.redis.msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;
@Configuration
public class RedisMsgListener {
@Autowired
Receiver receiver;
/**
* redis消息隊列監聽信息
*
* @param connectionFactory
* @param listenerAdapter
* @return
*/
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
container.addMessageListener(listenerAdapter, new PatternTopic("dealFaBuDingYue"));
return container;
}
/**
* 監聽方法
*
* @return
*/
@Bean(name = "listenerAdapter")
MessageListenerAdapter listenerAdapter() {
// 回調數據處理方法
return new MessageListenerAdapter(receiver, "dealJt");
}
}
package com.example.myframe.redis.msg;
import com.example.myframe.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service("receiver")
public class Receiver{
@Autowired
private RedisService redisService;
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 清除外部廣告位本地緩存
* @param message
*/
public void dealJt(String message){
System.out.println("我是用來監聽信息的");
System.out.println(message);
}
/**
* 清除外部廣告位本地緩存
* @param message
*/
public void dealJt1(String message){
System.out.println("我是用來監聽信息的1");
System.out.println(message);
}
}