SpringBoot中Redis的基础使用

打印 上一主题 下一主题

主题 879|帖子 879|积分 2637

基础使用

首先引入依赖
  1.         <dependency>
  2.             <groupId>org.springframework.boot</groupId>
  3.             <artifactId>spring-boot-starter-data-redis</artifactId>
  4.         </dependency>
  5.         <dependency>
  6.             <groupId>redis.clients</groupId>
  7.             <artifactId>jedis</artifactId>
  8.             <version>2.9.0</version>
  9.         </dependency>
复制代码
然后在application.yml的spring下增加redis配置:

代码如下
  1. redis:
  2.     # Redis数据库索引(默认为0)
  3.     database: 0
  4.     # Redis服务器地址
  5.     host: 127.0.0.1
  6.     # Redis服务器连接端口
  7.     port: 6379
  8.     password: '123456'
  9.     jedis:
  10.       pool:
  11.         # 连接池最大连接数(使用负值表示没有限制)
  12.         max-active: 8
  13.         # 连接池最大阻塞等待时间(使用负值表示没有限制)
  14.         max-wait: 1
  15.         # 连接池中的最大空闲连接
  16.         max-idle: 8
  17.         # 连接池中的最小空闲连接
  18.         min-idle: 0
  19.     # 连接超时时间(毫秒)
  20.     timeout: 5000
复制代码
然后在根包下创建一个service的文件夹加,然后在里面增加redis文件夹,redis文件夹里编写redis的基础操作函数。
编写IRedisService接口,编写增删改查函数,代码如下:
  1. import java.util.Map;
  2. @Service
  3. public interface IRedisService {
  4.     /**
  5.      * 加入元素
  6.      * @param key
  7.      * @param value
  8.      */
  9.     void  setValue(String key, Map<String, Object> value);
  10.     /**
  11.      * 加入元素
  12.      * @param key
  13.      * @param value
  14.      */
  15.     void  setValue(String key, String value);
  16.     /**
  17.      * 加入元素
  18.      * @param key
  19.      * @param value
  20.      */
  21.     void   setValue(String key, Object value);
  22.     /**
  23.      * 获取元素
  24.      * @param key
  25.      */
  26.     Object getMapValue(String key);
  27.     /**
  28.      * 获取元素
  29.      * @param key
  30.      */
  31.     Object getValue(String key);
  32. }
复制代码
编写RedisServiceImpl实现,实现Redis的增删改查。
  1. package com.example.dynamicdb.service.redis;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.data.redis.core.ValueOperations;
  5. import org.springframework.stereotype.Service;
  6. import java.util.Map;
  7. import java.util.concurrent.TimeUnit;
  8. @Service("RedisServiceImpl")
  9. public class RedisServiceImpl implements IRedisService {
  10.     public RedisServiceImpl(){}
  11.     @Autowired
  12.     private RedisTemplate redisTemplate;
  13.     @Override
  14.     public void setValue(String key, Map<String, Object> value) {
  15.         ValueOperations<String, Object> vo = redisTemplate.opsForValue();
  16.         vo.set(key, value);
  17.         redisTemplate.expire(key, 1, TimeUnit.HOURS);
  18.     }
  19.     @Override
  20.     public Object getValue(String key) {
  21.         ValueOperations<String, String> vo = redisTemplate.opsForValue();
  22.         return vo.get(key);
  23.     }
  24.     @Override
  25.     public void setValue(String key, String value) {
  26.         ValueOperations<String, Object> vo = redisTemplate.opsForValue();
  27.         vo.set(key, value);
  28.         redisTemplate.expire(key, 1, TimeUnit.HOURS);
  29.     }
  30.     @Override
  31.     public void setValue(String key, Object value) {
  32.         ValueOperations<String, Object> vo = redisTemplate.opsForValue();
  33.         vo.set(key, value);
  34.         redisTemplate.expire(key, 1, TimeUnit.HOURS);
  35.     }
  36.     @Override
  37.     public Object getMapValue(String key) {
  38.         ValueOperations<String, String> vo = redisTemplate.opsForValue();
  39.         return vo.get(key);
  40.     }
  41. }
复制代码
然后创建一个RedisController,编写一个测试接口,如下:
  1. @RestController
  2. public class RedisController {
  3.     @Resource(name = "RedisServiceImpl")//使用resource实例化对象,name是指定实例化的类,用于一个接口多个类继承的情况
  4.     private IRedisService iRedisService;
  5.     @PostMapping(value = "/Redis/TestRedis")
  6.     @ApiOperation(value = "redis测试接口", notes = "redis测试接口", httpMethod = "POST")
  7.     public String TestRedis(){
  8.         iRedisService.setValue("redis", "这是redis的测试数据");
  9.         Object redis = iRedisService.getValue("redis");
  10.         return redis.toString();
  11.     }
  12. }
复制代码
redis缓存使用

首先创建一个config文件夹,然后创建一个RedisCacheConfig文件,代码如下:
  1. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  2. import com.fasterxml.jackson.annotation.PropertyAccessor;
  3. import com.fasterxml.jackson.databind.ObjectMapper;
  4. import org.springframework.cache.annotation.EnableCaching;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  8. import org.springframework.data.redis.cache.RedisCacheManager;
  9. import org.springframework.data.redis.cache.RedisCacheWriter;
  10. import org.springframework.data.redis.connection.RedisConnectionFactory;
  11. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  12. import org.springframework.data.redis.serializer.RedisSerializationContext;
  13. import java.time.Duration;
  14. import java.util.HashMap;
  15. import java.util.Map;
  16. @EnableCaching
  17. @Configuration
  18. public class RedisCacheConfig {
  19.     /**
  20.      * 最新版,设置redis缓存过期时间
  21.      */
  22.     @Bean
  23.     public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
  24.         return new RedisCacheManager(
  25.                 RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
  26.                 this.getRedisCacheConfigurationWithTtl( 60), // 默认策略,未配置的 key 会使用这个
  27.                 this.getRedisCacheConfigurationMap() // 指定 key 策略
  28.         );
  29.     }
  30.     private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
  31.         Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
  32.         //SsoCache和BasicDataCache进行过期时间配置
  33.         redisCacheConfigurationMap.put("messagCache", this.getRedisCacheConfigurationWithTtl(30 * 60));
  34.         //自定义设置缓存时间
  35.         redisCacheConfigurationMap.put("studentCache", this.getRedisCacheConfigurationWithTtl(60 ));
  36.         return redisCacheConfigurationMap;
  37.     }
  38.     private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
  39.         Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
  40.         ObjectMapper om = new ObjectMapper();
  41.         om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  42.         om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  43.         jackson2JsonRedisSerializer.setObjectMapper(om);
  44.         RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
  45.         redisCacheConfiguration = redisCacheConfiguration.serializeValuesWith(
  46.                 RedisSerializationContext
  47.                         .SerializationPair
  48.                         .fromSerializer(jackson2JsonRedisSerializer)
  49.         ).entryTtl(Duration.ofSeconds(seconds));
  50.         return redisCacheConfiguration;
  51.     }
  52. }
复制代码
类名上有注解@Configuration,代表该类会在启动时加入进bean集合。
然后在RedisController下编写测试函数,如下:
  1. @Autowired
  2.     private SqlSession sqlSession;
  3.     @GetMapping(value = "/Redis/TestRedisCache")
  4.     @ResponseBody
  5.     @DS("db2")
  6.     @Cacheable(cacheNames = "userCache", key = "#id")
  7.     @ApiOperation(value="查询单条记录",notes = "查询")
  8.     public List<user> TestRedisCache(Integer id) {
  9.         //读取第二个数据库的值
  10.         UserMapper mapper = sqlSession.getMapper(UserMapper.class);
  11.         List<user> users = mapper.test();
  12.         return users;
  13.     }
复制代码
使用@Cacheable注解缓存接口的返回值,cacheNames的值和key的值,组合起来成为是缓存中的键值对的key值,如下图。

----------------------------------------------------------------------------------------------------
到此,SpringBoot中Redis的基础使用就已经介绍完了。
代码已经传到Github上了,欢迎大家下载。
Github地址:https://github.com/kiba518/dynamicdb
----------------------------------------------------------------------------------------------------
注:此文章为原创,任何形式的转载都请联系作者获得授权并注明出处!
若您觉得这篇文章还不错,请点击下方的【推荐】,非常感谢!
https://www.cnblogs.com/kiba/p/17480377.html
 
 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

冬雨财经

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表