java-redis
pom.xml添加如下配置:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.4.3</version> </dependency>
添加redis 配置类:
/** * @author * @date: 2019-01-09 11:14 * @des: redis配置 */ @Configuration public class RedisTemplateConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer(); // 设置值(value)的序列化采用FastJsonRedisSerializer。 redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // 设置键(key)的序列化采用StringRedisSerializer。 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
redisUtil常用方法工具类(可根据具体情况添加):
/** * @author * @date: 2019-01-09 11:14 * @des: redis工具类 */ @Component public class RedisUtil { @Autowired StringRedisTemplate stringRedisTemplate; @Autowired RedisTemplate<String, Object> redisTemplate; /** * TODO 判断key是否存在 * @param key * @return */ public boolean hasKey(String key){ try { return redisTemplate.hasKey(key); }catch (Exception e){ e.printStackTrace(); return false; } } /** * TODO 添加键值对 * @param key * @param value */ public void append(String key,String value){ stringRedisTemplate.opsForValue().append(key,value); } /** * TODO 根据key获取值 * @param key * @return */ public String get(String key){ return stringRedisTemplate.opsForValue().get(key); } /** * TODO incr * @param key * @param delta 要增加几(大于0) * @return */ public long incr(String key, long delta){ if(delta<0){ throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } }