Springboot統合redis(ソースコード)
56162 ワード
Springbootプロジェクト構成redis
application.ymlファイルredis構成
Springbootプロジェクトmaven構成
redis構成
redisデータ期限切れイベント処理
redisリスニング情報構成
redisリスニングメッセージ処理
redisデータ処理ツールクラス
作者の能力は有限で、もし问题があれば批判の指摘を歓迎します!!!
application.ymlファイルredis構成
redis:
#
# ( 0)
database: 1
host: 127.0.0.1
port: 6379
password: XXX
pool:
max-active: 8
max-wait: -1
max-idle: 20
min-idle: 0
timeout: 30000
Springbootプロジェクトmaven構成
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.67</version>
</dependency>
redis構成
@Configuration
@EnableCaching //
// CachingConfigurerSupport, KEY 。 。
public class RedisConfig extends CachingConfigurerSupport {
/**
* @Description: key + + key
* @Author: Mr.Jkx
* @date: 2020/3/24 13:16
*/
@Bean
@Override
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... 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();
}
};
}
/**
* @Description:
* @Author: Mr.Jkx
* @date: 2020/3/24 13:17
*/
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
// Spring RedisCacheConfiguration , redis ,
// , RedisCacheManager builder.build() cacheManager:
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig(); // , config
config = config.entryTtl(Duration.ofMinutes(1)) // , Duration
.disableCachingNullValues(); //
// set
Set<String> cacheNames = new HashSet<>();
cacheNames.add("my-redis-cache1");
cacheNames.add("my-redis-cache2");
//
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("my-redis-cache1", config);
configMap.put("my-redis-cache2", config.entryTtl(Duration.ofSeconds(120)));
RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory) // cacheManager
.initialCacheNames(cacheNames) // , ,
.withInitialCacheConfigurations(configMap)
.build();
return cacheManager;
}
/**
* @Description: ( alibaba >>> FastJsonRedisSerializer)
* @Author: Mr.Jkx
* @date: 2020/4/16 18:03
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
// AutoType
ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
// (value) FastJsonRedisSerializer。
redisTemplate.setValueSerializer(fastJsonRedisSerializer);
redisTemplate.setHashValueSerializer(fastJsonRedisSerializer);
// (key) StringRedisSerializer。
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
stringRedisTemplate.setConnectionFactory(factory);
return stringRedisTemplate;
}
}
redisデータ期限切れイベント処理
/**
* @program: youpin
* @description: redis
* @author: Mr.Jkx
* @create: 2020-04-16 18:52
*/
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
private static final Logger LOGGER = (Logger) LoggerFactory.getLogger(RedisKeyExpirationListener.class);
public RedisKeyExpirationListener(RedisMessageListenerContainer container) {
super(container);
}
/**
* @Description: redis ,
*
* ,
* @Author: Mr.Jkx
* @date: 2020/4/16 18:58
*/
@Override
public void onMessage(Message message, byte[] pattern) {
// key
String key = message.toString();
LOGGER.info("----redis listener get data key:{}----", key);
// key key(startsWith: )
if (key != null && key.startsWith("redis_")) {
// id,
String orderId = key.substring(8);
// id TODO
}
}
}
redisリスニング情報構成
/**
* @program: youpin
* @description: redis
* @author: Mr.Jkx
* @create: 2020-04-16 18:37
*/
@Configuration
public class RedisListenerConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory, MessageListenerAdapter listenerAdapter) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
// messageListener, “redisListener”
container.addMessageListener(listenerAdapter, new PatternTopic("redisListener"));
return container;
}
/**
* , ,
*
* @param redisReceiver
* @return
*/
@Bean
MessageListenerAdapter listenerAdapter(RedisReceiver redisReceiver) {
// messageListenerAdapter , “receiveMessage”
// , handleMessage
return new MessageListenerAdapter(redisReceiver, "receiveMessage");
}
// redis
@Bean
StringRedisTemplate template(RedisConnectionFactory connectionFactory) {
return new StringRedisTemplate(connectionFactory);
}
}
redisリスニングメッセージ処理
/**
* @program: youpin
* @description: ( )
* @author: Mr.Jkx
* @create: 2020-04-17 16:57
*/
@Component
public class RedisReceiver {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisReceiver.class);
/**
* @Description:
* @Author: Mr.Jkx
* @date: 2020/4/17 17:30
* “RedisListenerConfig”
*/
public void receiveMessage(String message) {
LOGGER.info(" :" + message);
}
}
redisデータ処理ツールクラス
/**
* @program: youpin
* @description: redis
* @author: Mr.Jkx
* @create: 2020-03-24 13:13
*/
@Service
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) {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
return operations.get(key);
}
/**
*
*
* @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);
}
/**
*
*
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
*
*
* @param key
* @param hashKey
* @return
*/
public Long hmDel(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.delete(key, hashKey);
}
/**
*
*
* @param key
* @param hashKey
* @param index
* @return
*/
public Long hmcompute(String key, Object hashKey, long index) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.increment(key, hashKey, index);
}
/**
*
*
* @param k
* @param v
*/
public void rPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
*
*
* @param k
* @param timeout
* @param unit
* @return
*/
public Object leftPop(String k, long timeout, TimeUnit unit) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.leftPop(k, timeout, unit);
}
/**
*
*
* @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
* @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);
}
/**
* @Description: redis ,
* @Author: Mr.Jkx
* @date: 2020/4/17 17:09
*/
public void sendChannelMess(String channel, Object message) {
redisTemplate.convertAndSend(channel, message);
}
}
作者の能力は有限で、もし问题があれば批判の指摘を歓迎します!!!