1、引入maven依赖
<dependency><groupId>org.springframework.bootgroupId><artifactId>spring-boot-starter-data-redisartifactId> dependency>
2、redis连接配置
spring:redis:host: 10.220.1.41port: 6379timeout: 10000password:jedis:pool:#最大连接数max-active: 8#最大阻塞等待时间(负数表示没限制)max-wait: -1ms#最大空闲max-idle: 8#最小空闲min-idle: 0
3、redisTemplate配置,其实springboot2不配置也是可以直接使用的,但是我们可以指定一下key,value序列化的方式,如下
@Configuration public class RedisConfiguration extends CachingConfigurerSupport {@Bean@Overridepublic 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();};}@Beanpublic CacheManager cacheManager(RedisConnectionFactory connectionFactory) {return RedisCacheManager.builder(connectionFactory).build();}@Beanpublic RedisTemplateredisTemplate(RedisConnectionFactory redisConnectionFactory){RedisTemplate redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(redisConnectionFactory);redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());redisTemplate.setHashKeySerializer(new StringRedisSerializer());redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());redisTemplate.afterPropertiesSet();return redisTemplate;} }
4、KeyPrefix类定义,方便管理key的前缀与超时时间(防止key管理混乱,出现后面的key覆盖前面的key的情况)
public class KeyPrefix {private String prefix;private Long timeout;//0或负数或空是表示永不过期public KeyPrefix(String prefix, Long timeout) {this.prefix = prefix;this.timeout = timeout;}
//所有的key前缀统一在这了定义,方便管理public static KeyPrefix LOGIN_USER_KP = new KeyPrefix("login_user_",10000L);public String getPrefix() {return prefix;}public void setPrefix(String prefix) {this.prefix = prefix;}public Long getTimeout() {return timeout;}public void setTimeout(Long timeout) {this.timeout = timeout;} }
5、写一个通用的服务类,键值对的插入和查询等
@Component public class RedisService{private RedisTemplate redisTemplate;private HashOperations hashOperations;private ListOperations listOperations;private ZSetOperations zSetOperations;private SetOperations setOperations;private ValueOperations valueOperations;@Autowiredpublic RedisService(RedisTemplate redisTemplate) {this.redisTemplate = redisTemplate;this.hashOperations = redisTemplate.opsForHash();this.listOperations = redisTemplate.opsForList();this.zSetOperations = redisTemplate.opsForZSet();this.setOperations = redisTemplate.opsForSet();this.valueOperations = redisTemplate.opsForValue();}public void hashPut(String key, HK hashKey, V value) {hashOperations.put(key, hashKey, value);}public Map hashFindAll(String key) {return hashOperations.entries(key);}public V hashGet(String key, HK hashKey) {return hashOperations.get(key, hashKey);}public void hashRemove(String key, HK hashKey) {hashOperations.delete(key, hashKey);}public Long listPush(String key, V value) {return listOperations.rightPush(key, value);}public Long listUnshift(String key, V value) {return listOperations.leftPush(key, value);}public List listFindAll(String key) {if (!redisTemplate.hasKey(key)) {return null;}return listOperations.range(key, 0, listOperations.size(key));}public V listLPop(String key) {return listOperations.leftPop(key);}public void setValue(String key, V value) {valueOperations.set(key, value);}public void setValue(KeyPrefix kp, String key, V value) {Long timeout = kp .getTimeout();if(timeout == null || timeout <= 0){this.setValue(kp.getPrefix() + key, value);}else{this.setValue(kp.getPrefix() + key, value, kp.getTimeout());}}public void setValue(String key, V value, long timeout) {valueOperations.set(key, value, timeout, TimeUnit.MILLISECONDS);}public V getValue(String key) {return valueOperations.get(key);}public void remove(String key) {redisTemplate.delete(key);}public boolean expire(String key, long timeout, TimeUnit timeUnit) {return redisTemplate.expire(key, timeout, timeUnit);}}
6、测试
@SpringBootTest @RunWith(SpringRunner.class) @Component public class SpringRedisTest {@Autowiredprivate RedisServiceredisService;@Testpublic void set(){Users user = new Users();user.setUserId(1L);user.setUsername("tom");user.setPassword("123");redisService.setValue("user_tom", user);}}