1:添加pom依赖
1. <!-- Spring Boot Redis依赖 --> 2. <!-- 注意:1.5版本的依赖和2.0的依赖不一样,注意看哦 1.5我记得名字里面应该没有“data”, 2.0必须是“spring-boot-starter-data-redis” 这个才行 --> 3. <dependency> 4. <groupId>org.springframework.boot</groupId> 5. <artifactId>spring-boot-starter-data-redis</artifactId> 6. <!-- 1.5的版本默认采用的连接池技术是jedis 2.0以上版本默认连接池是lettuce, 在这里采用jedis,所以需要排除lettuce的jar --> 7. <exclusions> 8. <exclusion> 9. <groupId>redis.clients</groupId> 10. <artifactId>jedis</artifactId> 11. </exclusion> 12. <exclusion> 13. <groupId>io.lettuce</groupId> 14. <artifactId>lettuce-core</artifactId> 15. </exclusion> 16. </exclusions> 17. </dependency> 18. 19. <!-- 添加jedis客户端 --> 20. <dependency> 21. <groupId>redis.clients</groupId> 22. <artifactId>jedis</artifactId> 23. </dependency> 24. 25. <!--spring2.0集成redis所需common-pool2 --> 26. <!-- 必须加上,jedis依赖此 --> 27. <!-- spring boot 2.0 的操作手册有标注 大家可以去看看 地址是:https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/ --> 28. <dependency> 29. <groupId>org.apache.commons</groupId> 30. <artifactId>commons-pool2</artifactId> 31. </dependency>
注意,如果其中的<dependency></dependency>报错,那么就在前面和后面加上</dependencies>如图
2:配置application.properties文件
1. #redis 2. spring.jpa.database=0 3. spring.redis.host=127.0.0.1 4. spring.redis.password= 5. spring.redis.port=6379 6. # 数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位 7. spring.redis.timeout=10000 8. 9. # 连接池配置,2.0中直接使用jedis或者lettuce配置连接池 10. # 最大活跃连接数,负数为不限制 11. spring.redis.jedis.pool.max-active=8 12. # 等待可用连接的最大时间,负数为不限制 13. spring.redis.jedis.pool.max-wait=-1 14. # 最大空闲连接数 15. spring.redis.jedis.pool.max-idle=8 16. # 最小空闲连接数 17. spring.redis.jedis.pool.min-idle=0
3:RedisConfiguration配置文件
1. package com.sjx.config; 2. 3. import com.fasterxml.jackson.annotation.JsonAutoDetect; 4. import com.fasterxml.jackson.annotation.PropertyAccessor; 5. import com.fasterxml.jackson.databind.ObjectMapper; 6. import org.slf4j.Logger; 7. import org.slf4j.LoggerFactory; 8. import org.springframework.beans.factory.annotation.Autowired; 9. import org.springframework.beans.factory.annotation.Value; 10. import org.springframework.boot.context.properties.ConfigurationProperties; 11. import org.springframework.cache.Cache; 12. import org.springframework.cache.CacheManager; 13. import org.springframework.cache.annotation.CachingConfigurerSupport; 14. import org.springframework.cache.annotation.EnableCaching; 15. import org.springframework.cache.interceptor.CacheErrorHandler; 16. import org.springframework.cache.interceptor.KeyGenerator; 17. import org.springframework.context.annotation.Bean; 18. import org.springframework.context.annotation.Configuration; 19. import org.springframework.data.redis.cache.RedisCacheManager; 20. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 21. import org.springframework.data.redis.core.RedisTemplate; 22. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; 23. import org.springframework.data.redis.serializer.RedisSerializer; 24. import org.springframework.data.redis.serializer.StringRedisSerializer; 25. import redis.clients.jedis.JedisPool; 26. import redis.clients.jedis.JedisPoolConfig; 27. 28. /** 29. * @ClassName: RedisConfiguration 30. * @Description:TODO(这里用一句话描述这个类的作用) 31. * @author: 沈均晓 32. * @date: 2018年9月19日 上午11:18:33 33. */ 34. @Configuration 35. // 必须加,使配置生效 36. @EnableCaching 37. public class RedisConfiguration extends CachingConfigurerSupport { 38. 39. /** 40. * Logger 41. */ 42. private static final Logger logger = LoggerFactory.getLogger(RedisConfiguration.class); 43. 44. @Autowired 45. private JedisConnectionFactory jedisConnectionFactory; 46. 47. @Bean 48. public KeyGenerator keyGenerator() { 49. // 设置自动key的生成规则,配置spring boot的注解,进行方法级别的缓存 50. // 使用:进行分割,可以很多显示出层级关系 51. // 这里其实就是new了一个KeyGenerator对象,只是这是lambda表达式的写法,我感觉很好用,大家感兴趣可以去了解下 52. return (target, method, params) -> { 53. StringBuilder sb = new StringBuilder(); 54. sb.append(target.getClass().getName()); 55. sb.append(":"); 56. sb.append(method.getName()); 57. for (Object obj : params) { 58. sb.append(":" + String.valueOf(obj)); 59. } 60. String rsToUse = String.valueOf(sb); 61. logger.info("自动生成Redis Key -> [{}]", rsToUse); 62. return rsToUse; 63. }; 64. } 65. 66. @Bean 67. public CacheManager cacheManager() { 68. // 初始化缓存管理器,在这里我们可以缓存的整体过期时间什么的,我这里默认没有配置 69. logger.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start"); 70. RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager.RedisCacheManagerBuilder 71. .fromConnectionFactory(jedisConnectionFactory); 72. return builder.build(); 73. } 74. 75. @Bean 76. public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) { 77. // 设置序列化 78. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); 79. ObjectMapper om = new ObjectMapper(); 80. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); 81. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); 82. jackson2JsonRedisSerializer.setObjectMapper(om); 83. // 配置redisTemplate 84. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>(); 85. redisTemplate.setConnectionFactory(jedisConnectionFactory); 86. RedisSerializer stringSerializer = new StringRedisSerializer(); 87. redisTemplate.setKeySerializer(stringSerializer); // key序列化 88. redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); // value序列化 89. redisTemplate.setHashKeySerializer(stringSerializer); // Hash key序列化 90. redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); // Hash value序列化 91. redisTemplate.afterPropertiesSet(); 92. return redisTemplate; 93. } 94. 95. @Override 96. @Bean 97. public CacheErrorHandler errorHandler() { 98. // 异常处理,当Redis发生异常时,打印日志,但是程序正常走 99. logger.info("初始化 -> [{}]", "Redis CacheErrorHandler"); 100. CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() { 101. @Override 102. public void handleCacheGetError(RuntimeException e, Cache cache, Object key) { 103. logger.error("Redis occur handleCacheGetError:key -> [{}]", key, e); 104. } 105. 106. @Override 107. public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) { 108. logger.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e); 109. } 110. 111. @Override 112. public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) { 113. logger.error("Redis occur handleCacheEvictError:key -> [{}]", key, e); 114. } 115. 116. @Override 117. public void handleCacheClearError(RuntimeException e, Cache cache) { 118. logger.error("Redis occur handleCacheClearError:", e); 119. } 120. }; 121. return cacheErrorHandler; 122. } 123. 124. /** 125. * 此内部类就是把yml的配置数据,进行读取,创建JedisConnectionFactory和JedisPool,以供外部类初始化缓存管理器使用 126. * 不了解的同学可以去看@ConfigurationProperties和@Value的作用 127. * 128. */ 129. @ConfigurationProperties 130. class DataJedisProperties { 131. @Value("${spring.redis.host}") 132. private String host; 133. @Value("${spring.redis.password}") 134. private String password; 135. @Value("${spring.redis.port}") 136. private int port; 137. @Value("${spring.redis.timeout}") 138. private int timeout; 139. @Value("${spring.redis.jedis.pool.max-idle}") 140. private int maxIdle; 141. @Value("${spring.redis.jedis.pool.max-wait}") 142. private long maxWaitMillis; 143. 144. @Bean 145. JedisConnectionFactory jedisConnectionFactory() { 146. logger.info("Create JedisConnectionFactory successful"); 147. JedisConnectionFactory factory = new JedisConnectionFactory(); 148. factory.setHostName(host); 149. factory.setPort(port); 150. factory.setTimeout(timeout); 151. factory.setPassword(password); 152. return factory; 153. } 154. 155. @Bean 156. public JedisPool redisPoolFactory() { 157. logger.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port); 158. JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); 159. jedisPoolConfig.setMaxIdle(maxIdle); 160. jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); 161. 162. JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password); 163. return jedisPool; 164. } 165. } 166. 167. }
4、在实现类中使用
1. package com.sjx.service.impl; 2. 3. import java.util.List; 4. 5. import javax.annotation.Resource; 6. 7. import org.springframework.beans.factory.annotation.Autowired; 8. import org.springframework.cache.annotation.Cacheable; 9. import org.springframework.data.redis.core.StringRedisTemplate; 10. import org.springframework.stereotype.Service; 11. 12. import com.alibaba.fastjson.JSON; 13. import com.sjx.dao.AttachmentDao; 14. import com.sjx.entity.Attachment; 15. import com.sjx.service.AttachmentService; 16. import com.sjx.util.ResultMap; 17. 18. @Service 19. public class AttachmentServiceImpl implements AttachmentService { 20. 21. @Resource 22. private AttachmentDao attachmentdao; 23. 24. @Autowired 25. StringRedisTemplate stringRedisTemplate; 26. 27. @Override 28. public ResultMap insertSelective(Attachment attachment) { 29. // TODO Auto-generated method stub 30. int insert = attachmentdao.insert(attachment); 31. if (insert < 0) { 32. return ResultMap.error("添加失败"); 33. } 34. return ResultMap.ok("添加成功"); 35. } 36. 37. @Override 38. public ResultMap deleteByPrimaryKey(Long id) { 39. // TODO Auto-generated method stub 40. int deleteByPrimaryKey = attachmentdao.deleteByPrimaryKey(id); 41. if (deleteByPrimaryKey < 0) { 42. return ResultMap.error("删除失败"); 43. } 44. return ResultMap.ok("删除成功"); 45. } 46. 47. @Override 48. public ResultMap selectByPrimaryKey(Long id) { 49. Attachment selectByPrimaryKey = attachmentdao.selectByPrimaryKey(id); 50. stringRedisTemplate.opsForValue().append("attachment",JSON.toJSONString(selectByPrimaryKey)); 51. ResultMap resultMap = new ResultMap(); 52. resultMap.put("Attachment", selectByPrimaryKey); 53. return resultMap; 54. } 55. 56. @Override 57. public ResultMap SelectiveSelectByAttachment(Attachment attachment) { 58. List<Attachment> selectiveSelectByAttachment = attachmentdao.SelectiveSelectByAttachment(attachment); 59. stringRedisTemplate.opsForList().leftPush("attachmentList", JSON.toJSONString(selectiveSelectByAttachment)); 60. ResultMap resultMap = new ResultMap(); 61. resultMap.put("Attachment", selectiveSelectByAttachment); 62. return resultMap; 63. } 64. 65. @Override 66. public ResultMap updateByPrimaryKeySelective(Attachment attachment) { 67. int updateByPrimaryKeySelective = attachmentdao.updateByPrimaryKeySelective(attachment); 68. if (updateByPrimaryKeySelective < 0) { 69. return ResultMap.error("更新失败"); 70. } 71. return ResultMap.ok("更新成功"); 72. } 73. 74. }
此篇文章借鉴CSDN博主:Shen_Junxiao
具体操作可以去他的文章查看,谢谢。(19条消息) SpringBoot使用redis详尽教程_springboot 默认关闭redis_Shen_Junxiao的博客-CSDN博客