Springboot整合redis及redis集群

深碍√TFBOYSˉ_ 2022-06-04 07:48 399阅读 0赞
  1. 1maven依赖
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. 2、配置文件application.properties在添加配置:
  7. #redis 集群
  8. spring.redis.cluster.nodes=192.168.94.130:7000, 192.168.94.130:7001, 192.168.94.130:7002, 192.168.94.130:7003, 192.168.94.130:7004, 192.168.94.130:7005
  9. #redis单个节点
  10. #spring.redis.database=0
  11. #spring.redis.host=192.168.94.130
  12. #spring.redis.port=6379
  13. #spring.redis.password=
  14. #spring.redis.pool.max-idle=8
  15. #spring.redis.pool.min-idle=0
  16. #spring.redis.pool.max-active=8
  17. #spring.redis.pool.max-wait=-1
  18. #spring.redis.timeout=5000
  19. 3redisTemplate测试:
  20. @Autowired
  21. RedisTemplate redisTemplate;
  22. @Test
  23. public void redisTest() {
  24. String key = "aaa";
  25. String value = "bbb";
  26. ValueOperations opsForValue = redisTemplate.opsForValue();
  27. //数据插入
  28. opsForValue.set(key, value);
  29. String valueFromRedis = opsForValue.get(key);
  30. System.out.println(valueFromRedis)
  31. //数据删除
  32. redisTemplate.delete(key);
  33. valueFromRedis = opsForValue.get(key);
  34. System.out.println(valueFromRedis)
  35. }
  36. 4.
  37. Spring boot工程测试:
  38. application.properties文件
  39. server.port=8080
  40. #mysql
  41. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  42. spring.datasource.url=jdbc:mysql://192.168.94.130:3306/mytest
  43. spring.datasource.username=xuhaixing
  44. spring.datasource.password=xuhaixing
  45. #spring.jpa.hibernate.naming-strategy=com.xhx.ms.entity.MySQLUpperCaseStrategy
  46. #redis
  47. #spring.redis.database=0
  48. #spring.redis.host=192.168.94.130
  49. #spring.redis.port=6379
  50. #spring.redis.password=
  51. #spring.redis.pool.max-idle=8
  52. #spring.redis.pool.min-idle=0
  53. #spring.redis.pool.max-active=8
  54. #spring.redis.pool.max-wait=-1
  55. #spring.redis.timeout=5000
  56. #redis 集群
  57. spring.redis.cluster.nodes=192.168.94.130:7000, 192.168.94.130:7001, 192.168.94.130:7002, 192.168.94.130:7003, 192.168.94.130:7004, 192.168.94.130:7005
  58. #jpa
  59. spring.jpa.database=mysql
  60. spring.jpa.show-sql=true
  61. spring.jpa.hibernate.ddl-auto=update
  62. javaConfig
  63. package com.xhx.ms.config;
  64. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  65. import com.fasterxml.jackson.annotation.PropertyAccessor;
  66. import com.fasterxml.jackson.databind.ObjectMapper;
  67. import com.sun.org.apache.xml.internal.utils.StringBufferPool;
  68. import org.springframework.cache.CacheManager;
  69. import org.springframework.cache.annotation.CachingConfigurerSupport;
  70. import org.springframework.cache.annotation.EnableCaching;
  71. import org.springframework.cache.interceptor.KeyGenerator;
  72. import org.springframework.context.annotation.Bean;
  73. import org.springframework.context.annotation.Configuration;
  74. import org.springframework.data.redis.cache.RedisCacheManager;
  75. import org.springframework.data.redis.connection.RedisConnectionFactory;
  76. import org.springframework.data.redis.core.RedisTemplate;
  77. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  78. import org.springframework.data.redis.serializer.StringRedisSerializer;
  79. import java.lang.reflect.Method;
  80. /**
  81. * redis缓存配置
  82. * Created by xuhaixing on 17-11-25.
  83. */
  84. @Configuration
  85. @EnableCaching//启用缓存
  86. public class RedisCacheConfig extends CachingConfigurerSupport {
  87. /**
  88. * 自定义key,此方法会根据类名+方法名+所有参数的值生成一个
  89. * 唯一的key,即@Cacheable中的key
  90. */
  91. @Override
  92. public KeyGenerator keyGenerator(){
  93. return new KeyGenerator() {
  94. @Override
  95. public Object generate(Object o, Method method, Object... objects) {
  96. StringBuilder sb = new StringBuilder();
  97. sb.append(o.getClass().getName());
  98. sb.append(method.getName());
  99. for(Object obj:objects){
  100. sb.append(obj.toString());
  101. }
  102. System.out.println(sb);
  103. return sb.toString();
  104. }
  105. };
  106. }
  107. /**
  108. * redisTemplate缓存操作类
  109. * @param redisConnectionFactory
  110. * @return
  111. */
  112. @Bean
  113. public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
  114. RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
  115. redisTemplate.setConnectionFactory(redisConnectionFactory);
  116. // StringRedisSerializer redisSerializer = new StringRedisSerializer();
  117. // redisTemplate.setKeySerializer(redisSerializer);
  118. // redisTemplate.setHashKeySerializer(redisSerializer);
  119. setSerializer(redisTemplate);
  120. return redisTemplate;
  121. }
  122. private void setSerializer(RedisTemplate template) {
  123. Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
  124. Object.class);
  125. ObjectMapper om = new ObjectMapper();
  126. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  127. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  128. jackson2JsonRedisSerializer.setObjectMapper(om);
  129. template.setValueSerializer(jackson2JsonRedisSerializer);
  130. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  131. }
  132. /**
  133. * 缓存管理器
  134. *
  135. */
  136. @Bean
  137. public CacheManager cacheManager(RedisTemplate<?,?> redisTemplate){
  138. RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
  139. redisCacheManager.setDefaultExpiration(3000);//s
  140. return redisCacheManager;
  141. }
  142. }
  143. Service注入缓存
  144. package com.xhx.ms.service;
  145. import com.xhx.ms.entity.Person;
  146. import com.xhx.ms.repository.PersonRepository;
  147. import org.springframework.beans.factory.annotation.Autowired;
  148. import org.springframework.cache.annotation.CacheEvict;
  149. import org.springframework.cache.annotation.Cacheable;
  150. import org.springframework.data.redis.core.RedisTemplate;
  151. import org.springframework.data.redis.core.ValueOperations;
  152. import org.springframework.stereotype.Repository;
  153. import org.springframework.stereotype.Service;
  154. import javax.annotation.Resource;
  155. /**
  156. * Created by xuhaixing on 17-11-25.
  157. */
  158. @Service
  159. public class PersonService {
  160. @Resource
  161. private PersonRepository personRepository;
  162. @Autowired
  163. private RedisTemplate<String,Object> redisTemplate;
  164. public void test(){
  165. ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
  166. valueOperations.set("mykey1","random1="+Math.random());
  167. System.out.println(valueOperations.get("mykey1"));
  168. }
  169. @Cacheable(value="person")
  170. public Person findById(String id){
  171. System.out.println("------findById-----id = "+id);
  172. return personRepository.findOne(id);
  173. }
  174. // @CacheEvict(value="person",allEntries=true) //删除全部
  175. @CacheEvict(value="person",key="'com.xhx.ms.service.PersonServicefindById'+#id") //删除指定
  176. public void deleteFromCache(String id){
  177. System.out.println("------deleteFromCache-----从缓存删除");
  178. }
  179. }
  180. @Cacheable会记住请求参数和返回值,只有第一次请求时执行了方法,后面请求都没有执行方法,清楚缓存后又执行方法
  181. 主方法
  182. package com.xhx.ms;
  183. import org.springframework.boot.SpringApplication;
  184. import org.springframework.boot.autoconfigure.SpringBootApplication;
  185. @SpringBootApplication
  186. public class SpringbootRedisApplication {
  187. public static void main(String[] args) {
  188. SpringApplication.run(SpringbootRedisApplication.class, args);
  189. }
  190. }

满意请支持一下:

SouthEast SouthEast 1

发表评论

表情:
评论列表 (有 0 条评论,399人围观)

还没有评论,来说两句吧...

相关阅读

    相关 SpringBoot整合redis

    一:缓存的应用场景 1:什么是缓存? 在互联网场景下,尤其 2C 端大流量场景下,需要将一些经常展现和不会频繁变更的数据,存放在存取速率更快的地方。缓存就是一个存储器,在技

    相关 springboot整合redis

    一、redis集群原理 redis集群中的所有节点彼此互联,节点内部采用二进制协议优化传输速度和带宽,每个节点都可以与Java客户端连接。redis集群的数据分配采用哈希