栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java > SpringBoot

SpringBoot之redis数据缓存管理

SpringBoot 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot之redis数据缓存管理

目标

实现数据缓存,如果缓存中没有数据,则从数据库查询,并且写入redis缓存,如果redis缓存中有数据,则直接从redis中读取,同事删除更新等操作也需要维护缓存。本文基于前面两篇文章而来,部分重复就不贴。

实现1、依赖

      
          org.springframework.boot
          spring-boot-starter-data-redis
      
      
          org.springframework.boot
          spring-boot-starter-web
      
      
          org.mybatis.spring.boot
          mybatis-spring-boot-starter
          1.3.2
      

      
          mysql
          mysql-connector-java
          runtime
      
      
          org.springframework.boot
          spring-boot-starter-test
          test
      

      
      
          org.apache.commons
          commons-pool2
      
  
2、配置redis跟mybatis

yml配置如下:

server:
  port: 8989spring:
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8    username: root    password: root  redis:
    host: 127.0.0.1
    port: 6379
    lettuce:
      pool:
        max-idle: 8
        min-idle: 0
        max-active: 8mybatis:
  config-location: classpath:/mybatis/config/mybatis-config.xml
  mapper-locations: classpath:/mybatis/mapper@EnableCaching@Configuration@AutoConfigureAfter(RedisAutoConfiguration.class)public class RedisConfig {    
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setValueSerializer(jackson2JsonRedisSerializer());        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer());
        template.afterPropertiesSet();        return template;
    }    
    @Bean
    public RedisSerializer jackson2JsonRedisSerializer() {        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper mapper = new ObjectMapper();
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);        return serializer;
    }    
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {        // 生成一个默认配置,通过config对象即可对缓存进行自定义配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();        // 设置缓存的默认过期时间,也是使用Duration设置
        config = config.entryTtl(Duration.ofMinutes(1))                // 设置 key为string序列化
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))                // 设置value为json序列化
                .serializevaluesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))                // 不缓存空值
                .disableCachingNullValues();        // 设置一个初始化的缓存空间set集合
        Set cacheNames = new HashSet<>();
        cacheNames.add("timeGroup");
        cacheNames.add("user");        // 对每个缓存空间应用不同的配置
        Map configMap = new HashMap<>();
        configMap.put("timeGroup", config);
        configMap.put("user", config.entryTtl(Duration.ofSeconds(120)));        // 使用自定义的缓存配置初始化一个cacheManager
        RedisCacheManager cacheManager = RedisCacheManager.builder(redisConnectionFactory)                // 一定要先调用该方法设置初始化的缓存名,再初始化相关的配置
                .initialCacheNames(cacheNames)
                .withInitialCacheConfigurations(configMap)
                .build();        return cacheManager;
    }
}

相比上节,我们多配置了一个缓存管理器,在springboot2中配置缓存管理是新的api也就是builder模式构建。然后通过@EnableCaching 开启缓存注解。然后需要注意的是 你在redistemplate中的配置的key,value序列化方法并不会生效,需要在RedisCacheConfiguration中单独配置。

3、使用caching注解

一般缓存在service层中使用。
代码如下

@Servicepublic class UserServiceImpl implements UserService {    @Autowired
    private UserMapper userMapper;    @Override
    public User saveUser(User user) {
        userMapper.save(user);        // 返回用户信息,带id
        return user;
    }    
    @CacheEvict(value = "user", key = "#root.args[0]", condition = "#result eq true")    @Override
    public Boolean removeUser(Long id) {        // 如果删除记录不为1  则是失败
        return userMapper.deleteById(id) == 1;
    }    
    @Cacheable(value = "user", key = "#root.args[0]", unless = "#result eq null ")    @Override
    public User getById(Long id) {        return userMapper.selectById(id);
    }    
    @CachePut(value = "user", key = "#root.args[0]", unless = "#user eq null ")    @Override
    public User updateUser(User user) {
        userMapper.update(user);        return user;
    }
}

其中每个注解的作用都写在注释中了。

4、测试

然后我们编写一下对应的rest接口来测试

@RequestMapping("/user")@RestControllerpublic class UserController {    @Autowired
    private UserService userService;    @PostMapping
    public User save(@RequestBody User user) {        return userService.saveUser(user);
    }    @PutMapping
    public User update(@RequestBody User user) {        return userService.updateUser(user);
    }    @DeleteMapping(value = "/id/{id}")    public Boolean delete(@PathVariable  Long id) {        return userService.removeUser(id);
    }    @GetMapping(value = "/id/{id}")    public User findById (@PathVariable Long id) {        return userService.getById(id);
    }

}

启动程序。首先访问http://localhost:8989/user/id/2
成功请求数据 并且控制台打印sql

image.png


查看redis是否成功缓存数据。

image.png


成功缓存数据,并且key为主键id。
再次刷新访问。

image.png


并没有打印sql,说明缓存生效,数据是从缓存中去的,而没有去访问数据库。
至于修改跟删除两个注解就交给大家测试。



作者:余空啊
链接:https://www.jianshu.com/p/6943bb8a9ab8


转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号