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 + "已过期-------------------");}
}