redis的Java客戶端
整合步驟
添加redis的pom依賴
<!-- 引入redis依賴 -->
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId>
</dependency><!-- 引入redis連接池的依賴 -->
<dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency>
配置文件配置
spring:redis:database: 0host: 127.0.0.1port: 6379password:timeout: 5000lettuce:pool:max-active: 32max-wait: -1max-idle: 16min-idle: 8
編寫配置類
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @author LH**/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();//使用fastjson序列化FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);// value值的序列化采用fastJsonRedisSerializertemplate.setValueSerializer(fastJsonRedisSerializer);template.setHashValueSerializer(fastJsonRedisSerializer);// key的序列化采用StringRedisSerializertemplate.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean(StringRedisTemplate.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}
}
編寫redis工具類RedisUtil.java
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** Redis常用的一些操作** @author LH*/
@Component
public class RedisUtil {@Resourceprivate RedisTemplate<String, Object> redisTemplate;/*** 寫入緩存*/public boolean set(final String key, Object value) {boolean result = false;try {ValueOperations<String, Object> operations = redisTemplate.opsForValue();operations.set(key, value);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 寫入緩存設置時效時間*/public boolean set(final String key, Object value, Long expireTime) {boolean result = false;try {ValueOperations<String, Object> operations = redisTemplate.opsForValue();operations.set(key, value);redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 更新緩存*/public boolean getAndSet(final String key, String value) {boolean result = false;try {redisTemplate.opsForValue().getAndSet(key, value);result = true;} catch (Exception e) {e.printStackTrace();}return result;}/*** 批量刪除對應的value*/public void remove(final String... keys) {for (String key : keys) {remove(key);}}/*** 批量刪除key*/public void removePattern(final String pattern) {Set<String> keys = redisTemplate.keys(pattern);if (CollectionUtils.isNotEmpty(keys)) {redisTemplate.delete(keys);}}/*** 刪除對應的value*/public void remove(final String key) {if (exists(key)) {redisTemplate.delete(key);}}/*** 判斷緩存中是否有對應的value*/public boolean exists(final String key) {Boolean isExists = redisTemplate.hasKey(key);return BooleanUtils.isTrue(isExists);}/*** 讀取緩存*/public Object get(final String key) {ValueOperations<String, Object> operations = redisTemplate.opsForValue();return operations.get(key);}/*** 哈希 添加*/public void hmSet(String key, Object hashKey, Object value) {HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();hash.put(key, hashKey, value);}/*** 哈希獲取數據*/public Object hmGet(String key, Object hashKey) {HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();return hash.get(key, hashKey);}/*** 列表添加*/public void lPush(String k, Object v) {ListOperations<String, Object> list = redisTemplate.opsForList();list.rightPush(k, v);}/*** 列表獲取*/public List<Object> lRange(String k, long l, long l1) {ListOperations<String, Object> list = redisTemplate.opsForList();return list.range(k, l, l1);}/*** 集合添加*/public void addSet(String key, Object value) {SetOperations<String, Object> set = redisTemplate.opsForSet();set.add(key, value);}/*** 刪除集合下的所有值*/public void removeSetAll(String key) {SetOperations<String, Object> set = redisTemplate.opsForSet();Set<Object> objectSet = set.members(key);if (objectSet != null && !objectSet.isEmpty()) {for (Object o : objectSet) {set.remove(key, o);}}}/*** 判斷set集合里面是否包含某個元素*/public Boolean isMember(String key, Object member) {SetOperations<String, Object> set = redisTemplate.opsForSet();return set.isMember(key, member);}/*** 集合獲取*/public Set<Object> setMembers(String key) {SetOperations<String, Object> set = redisTemplate.opsForSet();return set.members(key);}/*** 有序集合添加*/public void zAdd(String key, Object value, double source) {ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();zset.add(key, value, source);}/*** 有序集合獲取指定范圍的數據*/public Set<Object> rangeByScore(String key, double source, double source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.rangeByScore(key, source, source1);}/*** 有序集合升序獲取*/public Set<Object> range(String key, Long source, Long source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.range(key, source, source1);}/*** 有序集合降序獲取*/public Set<Object> reverseRange(String key, Long source, Long source1) {ZSetOperations<String, Object> zSet = redisTemplate.opsForZSet();return zSet.reverseRange(key, source, source1);}
}
redis Key過期處理事件
修改redis的配置文件
看一下notify-keyspace-events Ex
是否被注釋(默認是注釋),放開注釋即可。
修改RedisConfig.java
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** @Description redis配置* @Author LH**/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig
{@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){RedisTemplate<Object, Object> template = new RedisTemplate<>();//使用fastjson序列化FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);// value值的序列化采用fastJsonRedisSerializertemplate.setValueSerializer(fastJsonRedisSerializer);template.setHashValueSerializer(fastJsonRedisSerializer);// key的序列化采用StringRedisSerializertemplate.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}@Bean@ConditionalOnMissingBean(StringRedisTemplate.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory){StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}/*** 開啟監聽redis Key過期事件*/@Beanpublic RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory){RedisMessageListenerContainer container = new RedisMessageListenerContainer();container.setConnectionFactory(connectionFactory);return container;}
}
定義過期監聽器RedisKeyExpireListener
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;/*** @Description redis過期監聽器* @Author LH**/
@Slf4j
public class RedisKeyExpireListener extends KeyExpirationEventMessageListener
{public RedisKeyExpireListener(RedisMessageListenerContainer listenerContainer){super(listenerContainer);}@Overridepublic void onMessage(Message message, byte[] pattern){String expireKey = message.toString();// 根據過期的key處理對應的業務邏輯log.info(expireKey + "已過期-------------------");}
}