当前位置:Gxlcms > redis > SpringBoot如何集成redis

SpringBoot如何集成redis

时间:2021-07-01 10:21:17 帮助过:42人阅读

推荐(免费):redis教程

今天,日月在这里教大家如何使用springBoot集成redis,说实话比较简单,网上也有大把的教程。先套用一下网上的简介。
定义

REmote DIctionary Server(Redis) 是一个由Salvatore Sanfilippo写的key-value存储系统。
Redis是一个开源的使用ANSI C语言编写、遵守BSD协议、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库,并提供多种语言的API。
它通常被称为数据结构服务器,因为值(value)可以是 字符串(String), 哈希(Map), 列表(list), 集合(sets) 和 有序集合(sorted sets)等类型。
reids的优点

以下是Redis的一些优点。

异常快 - Redis非常快,每秒可执行大约110000次的设置(SET)操作,每秒大约可执行81000次的读取/获取(GET)操作。
支持丰富的数据类型 - Redis支持开发人员常用的大多数数据类型,例如列表,集合,排序集和散列等等。这使得Redis很容易被用来解决各种问题,因为我们知道哪些问题可以更好使用地哪些数据类型来处理解决。
操作具有原子性 - 所有Redis操作都是原子操作,这确保如果两个客户端并发访问,Redis服务器能接收更新的值。
多实用工具 - Redis是一个多实用工具,可用于多种用例,如:缓存,消息队列(Redis本地支持发布/订阅),应用程序中的任何短期数据,例如,web应用程序中的会话,网页命中计数等。

Redis 安装

Window 下安装
下载地址:https://github.com/MSOpenTech/redis/releases。
Redis 支持 32 位和 64 位。这个需要根据你系统平台的实际情况选择,这里我们下载 Redis-x64-xxx.zip压缩包到 C 盘,解压后,将文件夹重新命名为 redis。

打开一个 cmd 窗口 使用cd命令切换目录到 C:\redis
运行 redis-server.exe redis.windows.conf
如果想方便的话,可以把 redis 的路径加到系统的环境变量里,这样就省得再输路径了,后面的那个 redis.windows.conf 可以省略,如果省略,会启用默认的。输入之后,会显示如下界面:
在这里插入图片描述

集成redis

我们还是延用上一章的项目:Springboot集成springcloud-config实现dataSource热部署

1、添加依赖

  1. <!--集成redis-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-redis</artifactId>
  5. <version>1.4.1.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.alibaba</groupId>
  9. <artifactId>fastjson</artifactId>
  10. <version>1.2.3</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.fasterxml.jackson.core</groupId>
  14. <artifactId>jackson-databind</artifactId>
  15. </dependency>

2、在配置中心里添加redis配置

  1. spring.redis.host=127.0.0.1
  2. #Redis服务器连接端口
  3. spring.redis.port=6379
  4. #Redis服务器连接密码(默认为空)
  5. spring.redis.password=
  6. #连接池最大连接数(使用负值表示没有限制)
  7. spring.redis.pool.max-active=8
  8. #连接池最大阻塞等待时间(使用负值表示没有限制)
  9. spring.redis.pool.max-wait=-1
  10. #连接池中的最大空闲连接
  11. spring.redis.pool.max-idle=8
  12. #连接池中的最小空闲连接
  13. spring.redis.pool.min-idle=0
  14. #连接超时时间(毫秒)
  15. spring.redis.timeout=30000

3、配置类RedisConfig

  1. import java.lang.reflect.Method;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.cache.CacheManager;
  4. import org.springframework.cache.annotation.CachingConfigurerSupport;
  5. import org.springframework.cache.annotation.EnableCaching;
  6. import org.springframework.cache.interceptor.KeyGenerator;
  7. import org.springframework.cloud.context.config.annotation.RefreshScope;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.context.annotation.Configuration;
  10. import org.springframework.data.redis.cache.RedisCacheManager;
  11. import org.springframework.data.redis.connection.RedisConnectionFactory;
  12. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  13. import org.springframework.data.redis.core.RedisTemplate;
  14. import org.springframework.data.redis.core.StringRedisTemplate;
  15. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  16. import com.fasterxml.jackson.annotation.PropertyAccessor;
  17. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  18. import com.fasterxml.jackson.databind.ObjectMapper;
  19. @Configuration
  20. @EnableCaching
  21. @RefreshScope
  22. public class RedisConfig extends CachingConfigurerSupport{
  23. @Value("${spring.redis.host}")
  24. private String host;
  25. @Value("${spring.redis.port}")
  26. private int port;
  27. @Value("${spring.redis.timeout}")
  28. private int timeout;
  29. @Value("${spring.redis.password}")
  30. private String password;
  31. @Value("${spring.redis.pool.max-active}")
  32. private int maxActive;
  33. @Value("${spring.redis.pool.max-wait}")
  34. private int maxWait;
  35. @Value("${spring.redis.pool.max-idle}")
  36. private int maxIdle;
  37. @Value("${spring.redis.pool.min-idle}")
  38. private int minIdle;
  39. @RefreshScope
  40. @Bean
  41. public KeyGenerator wiselyKeyGenerator(){
  42. return new KeyGenerator() {
  43. @Override
  44. public Object generate(Object target, Method method, Object... params) {
  45. StringBuilder sb = new StringBuilder();
  46. sb.append(target.getClass().getName());
  47. sb.append(method.getName());
  48. for (Object obj : params) {
  49. sb.append(obj.toString());
  50. }
  51. return sb.toString();
  52. }
  53. };
  54. }
  55. @RefreshScope
  56. @Bean
  57. public JedisConnectionFactory redisConnectionFactory() {
  58. JedisConnectionFactory factory = new JedisConnectionFactory();
  59. factory.setHostName(host);
  60. factory.setPort(port);
  61. factory.setTimeout(timeout); //设置连接超时时间
  62. factory.setPassword(password);
  63. factory.getPoolConfig().setMaxIdle(maxIdle);
  64. factory.getPoolConfig().setMinIdle(minIdle);
  65. factory.getPoolConfig().setMaxTotal(maxActive);
  66. factory.getPoolConfig().setMaxWaitMillis(maxWait);
  67. return factory;
  68. }
  69. @RefreshScope
  70. @Bean
  71. public CacheManager cacheManager(RedisTemplate redisTemplate) {
  72. RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
  73. // Number of seconds before expiration. Defaults to unlimited (0)
  74. cacheManager.setDefaultExpiration(10); //设置key-value超时时间
  75. return cacheManager;
  76. }
  77. @RefreshScope
  78. @Bean
  79. public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
  80. StringRedisTemplate template = new StringRedisTemplate(factory);
  81. setSerializer(template); //设置序列化工具,这样ReportBean不需要实现Serializable接口
  82. template.afterPropertiesSet();
  83. return template;
  84. }
  85. @RefreshScope
  86. private void setSerializer(StringRedisTemplate template) {
  87. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  88. ObjectMapper om = new ObjectMapper();
  89. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  90. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  91. jackson2JsonRedisSerializer.setObjectMapper(om);
  92. template.setValueSerializer(jackson2JsonRedisSerializer);
  93. }
  94. }

4、RedisUtils类

  1. import java.io.Serializable;
  2. import java.util.List;
  3. import java.util.Set;
  4. import java.util.concurrent.TimeUnit;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.data.redis.core.HashOperations;
  7. import org.springframework.data.redis.core.ListOperations;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.core.SetOperations;
  10. import org.springframework.data.redis.core.ValueOperations;
  11. import org.springframework.data.redis.core.ZSetOperations;
  12. import org.springframework.stereotype.Service;
  13. @Service
  14. public class RedisUtils {
  15. @Autowired
  16. private RedisTemplate redisTemplate;
  17. /**
  18. * 写入缓存
  19. * @param key
  20. * @param value
  21. * @return
  22. */
  23. public boolean set(final String key, Object value) {
  24. boolean result = false;
  25. try {
  26. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  27. operations.set(key, value);
  28. result = true;
  29. } catch (Exception e) {
  30. e.printStackTrace();
  31. }
  32. return result;
  33. }
  34. /**
  35. * 写入缓存设置时效时间
  36. * @param key
  37. * @param value
  38. * @return
  39. */
  40. public boolean set(final String key, Object value, Long expireTime ,TimeUnit timeUnit) {
  41. boolean result = false;
  42. try {
  43. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  44. operations.set(key, value);
  45. redisTemplate.expire(key, expireTime, timeUnit);
  46. result = true;
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. }
  50. return result;
  51. }
  52. /**
  53. * 批量删除对应的value
  54. * @param keys
  55. */
  56. public void remove(final String... keys) {
  57. for (String key : keys) {
  58. remove(key);
  59. }
  60. }
  61. /**
  62. * 批量删除key
  63. * @param pattern
  64. */
  65. public void removePattern(final String pattern) {
  66. Set<Serializable> keys = redisTemplate.keys(pattern);
  67. if (keys.size() > 0){
  68. redisTemplate.delete(keys);
  69. }
  70. }
  71. /**
  72. * 删除对应的value
  73. * @param key
  74. */
  75. public void remove(final String key) {
  76. if (exists(key)) {
  77. redisTemplate.delete(key);
  78. }
  79. }
  80. /**
  81. * 判断缓存中是否有对应的value
  82. * @param key
  83. * @return
  84. */
  85. public boolean exists(final String key) {
  86. return redisTemplate.hasKey(key);
  87. }
  88. /**
  89. * 读取缓存
  90. * @param key
  91. * @return
  92. */
  93. public Object get(final String key) {
  94. Object result = null;
  95. ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
  96. result = operations.get(key);
  97. return result;
  98. }
  99. /**
  100. * 哈希 添加
  101. * @param key
  102. * @param hashKey
  103. * @param value
  104. */
  105. public void hmSet(String key, Object hashKey, Object value){
  106. HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
  107. hash.put(key,hashKey,value);
  108. }
  109. /**
  110. * 哈希获取数据
  111. * @param key
  112. * @param hashKey
  113. * @return
  114. */
  115. public Object hmGet(String key, Object hashKey){
  116. HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
  117. return hash.get(key,hashKey);
  118. }
  119. /**
  120. * 列表添加
  121. * @param k
  122. * @param v
  123. */
  124. public void lPush(String k,Object v){
  125. ListOperations<String, Object> list = redisTemplate.opsForList();
  126. list.rightPush(k,v);
  127. }
  128. /**
  129. * 列表获取
  130. * @param k
  131. * @param l
  132. * @param l1
  133. * @return
  134. */
  135. public List<Object> lRange(String k, long l, long l1){
  136. ListOperations<String, Object> list = redisTemplate.opsForList();
  137. return list.range(k,l,l1);
  138. }
  139. /**
  140. * 集合添加
  141. * @param key
  142. * @param value
  143. */
  144. public void add(String key,Object value){
  145. SetOperations<String, Object> set = redisTemplate.opsForSet();
  146. set.add(key,value);
  147. }
  148. /**
  149. * 集合获取
  150. * @param key
  151. * @return
  152. */
  153. public Set<Object> setMembers(String key){
  154. SetOperations<String, Object> set = redisTemplate.opsForSet();
  155. return set.members(key);
  156. }
  157. /**
  158. * 有序集合添加
  159. * @param key
  160. * @param value
  161. * @param scoure
  162. */
  163. public void zAdd(String key,Object value,double scoure){
  164. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  165. zset.add(key,value,scoure);
  166. }
  167. /**
  168. * 有序集合获取
  169. * @param key
  170. * @param scoure
  171. * @param scoure1
  172. * @return
  173. */
  174. public Set<Object> rangeByScore(String key,double scoure,double scoure1){
  175. ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
  176. return zset.rangeByScore(key, scoure, scoure1);
  177. }

5、测试,修改controller

  1. import java.util.concurrent.TimeUnit;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.PathVariable;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RestController;
  8. import com.chenqi.springboot.redis.RedisUtils;
  9. import com.chenqi.springboot.service.TestService;
  10. @RestController
  11. public class SpringBootController {
  12. public static final Logger log = LoggerFactory.getLogger(SpringBootController.class);
  13. @Autowired
  14. TestService testService;
  15. @Autowired
  16. private RedisUtils redisUtils;
  17. @RequestMapping(value = "/hello/{id}")
  18. public String hello(@PathVariable(value = "id") String id){
  19. //查询缓存中是否存在
  20. boolean hasKey = redisUtils.exists(id);
  21. String str = "";
  22. if(hasKey){
  23. //获取缓存
  24. Object object = redisUtils.get(id);
  25. log.info("从缓存获取的数据"+ object);
  26. str = object.toString();
  27. }else{
  28. //从数据库中获取信息
  29. log.info("从数据库中获取数据");
  30. str = testService.test();
  31. //数据插入缓存(set中的参数含义:key值,user对象,缓存存在时间10(long类型),时间单位)
  32. redisUtils.set(id,str,10L,TimeUnit.MINUTES);
  33. log.info("数据插入缓存" + str);
  34. }
  35. return str;
  36. }
  37. }

启动项目,第一次访问:http://localhost:8002/hello/111
在这里插入图片描述
在这里插入图片描述
通过控制台输出,我们可以看到是从数据库中获取的数据,并且存入了redis缓存中。

我们再次刷新浏览器
在这里插入图片描述
可以看到,第二次是从缓存中读取的,我们试试不断刷新浏览器
在这里插入图片描述
可以看到,之后都是从缓存中获取的。

到此我们的redis就配置好了。

SpringBoot集成Redis-demo下载
急需demo的兄弟就自行下载吧,不急可以留言邮箱,一般48小时内会发。

更多相关学习敬请关注redis栏目!

以上就是SpringBoot如何集成redis的详细内容,更多请关注gxlcms其它相关文章!

人气教程排行