pom.xml添加以下配置:redis
<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 配置類:spring
/** * @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經常使用方法工具類(可根據具體狀況添加):apache
/** * @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); } }