欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot2.x整合Redis进行数据缓存

程序员文章站 2022-07-07 11:38:04
...

SpringBoot2.x配置使用Redis

pom文件中引入:

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>

启动类标注:@EnableCaching

application.properties:

spring.redis.host=0.0.0.0 	#redis所在的服务器ip地址

SpringBoot2.x的Reids配置模板

目的:将缓存数据的Key存为String类型,Value则以json的格式存储在redis中,在读取缓存时,同样返回json格式

@Configuration
public class MyRedisConfig {
    /*
        SpringBoot2.x的ReidsCacheManager自定义配置方法
        缓存之后,key会多一个前缀,默认是将CacheName作为key的前缀
     */
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
        RedisSerializer<String> redisSerializer = new StringRedisSerializer();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);

        //解决查询缓存转换异常的问题
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 配置序列化(解决乱码的问题)
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
                // 缓存有效期60s
                //.entryTtl(Duration.ofSeconds(60))
                // 设置key序列化               .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))
                // 设置value序列化            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
                // 不缓存null值
                .disableCachingNullValues();
        RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(config)
                .build();
        System.out.println("ReidsCacheManager自定义配置方法被调用了...");
        return cacheManager;
    }
}



写一个Controller进行测试:

@Mapper
public interface DepartmentMapper {
    @Select("select * from department where id = #{id}")
    public Department getDeptById(Integer id);
}

@Service
public class DeptService {
    @Resource
    private DepartmentMapper departmentMapper;
    
    @Cacheable(cacheNames = "dept")
    public Department getDeptById(Integer id){
        System.out.println("查询的部门是:"+id);
        return departmentMapper.getDeptById(id);
    }

@RestController
public class DeptController {
    @Resource
    private DeptService deptService;

    @GetMapping("/dept/{id}")
    public Department getDept(@PathVariable("id") Integer id) {
        return deptService.getDeptById(id);
    }
}

第一次向浏览器请求,会先从数据库查找,再将查找到的数据缓存到Redis中,我们配置了Redis的缓存格式(json),存储数据如下:

SpringBoot2.x整合Redis进行数据缓存

我们再向浏览器发送同一个查找请求,此时不再查找数据库,而是使用Redis中的缓存数据:

SpringBoot2.x整合Redis进行数据缓存

相关标签: Spring全家桶