SpringBoot使用Redis作为缓存中间件

本文介绍了如何在SpringBoot应用中使用Redis作为缓存中间件。内容包括在application.properties中配置Redis连接信息,设置缓存管理器,启用缓存注解,并详细讲解了@CacheConfig、@Cacheable、@CachePut和@CacheEvict的用法。同时,提醒注意被缓存的数据对象需要实现Serializable接口以支持JSON序列化。

1. application.properties中配置

spring.redis.host=localhost

2. 配置缓存相关(缓存管理器)

@Configuration
public class MyRedisConfig {

    /**
     * 缓存管理器
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        //初始化一个RedisCacheWriter
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        //设置CacheManager的值序列化方式为json序列化
        RedisSerializer<Object> jsonSerializer = new GenericJackson2JsonRedisSerializer();
        RedisSerializationContext.SerializationPair<Object> pair = RedisSerializationContext.SerializationPair
                .fromSerializer(jsonSerializer);
        RedisCacheConfiguration defaultCacheConfig=RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(pair);
        //设置默认超过期时间是30秒
        defaultCacheConfig.entryTtl(Duration.ofSeconds(30));
        //初始化RedisCacheManager
        return new RedisCacheManager(redisCacheWriter, defaultCacheConfig);
    }
}

3. 声明使用缓存(在主类加@EnableCaching)

@SpringBootApplication
@EnableCaching
public class HelloApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloApplication.class, args);
    }

}

4. 使用缓存(@CacheConfig,@Cacheable,@CachePut,@CacheEvict的使用)

@CacheConfig(cacheNames = "emp", cacheManager = "cacheManager")
@Service
public class EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    /**
     * 将方法的运行结果进行缓存,以后再要相同的数据,直接从缓存中获取,不需要调用方法
     * CacheManager管理多个Cache组件,对缓存真正的CRUD在cache中
     *
     * cache几个属性
     *  cacheName/value: 指定缓存组件的名字
     *  key: 缓存数据使用的key,可以用它来指定。默认是方法参数的值
     *  keyGenerator:key生成器, 可以自己指定key生成器组件id .
     *      ps: key和keyGenerator二选一即可
     *  condition:指定符合条件下才缓存 condition = "#id > 3"
     *  unless:否定缓存,当unless指定条件为true,方法返回值就不会被缓存
     *      unless = "#result == null"
     *  sync:是否使用异步模式
     *
     * 运行流程
     * Cacheable
     *  1. 方法运行前,先去查询Cache(缓存组件),按照cacheName指定名字获取
     *      CacheManager先获取相应缓存,第一次获取缓存如果没有Cache组件,则会自动创建
     *  2. 去Cahce中查询缓存内容,使用一个key
     *  3. 没有查到缓存就调用目标方法
     *  4. 将目标方法返回的结果,放进缓存中
     *
     * @param id
     * @return
     */
    @Cacheable()
    public Employee getEmployee(Integer id) {
        System.out.println("---> 查询" + id + "号员工");
        return employeeMapper.getEmployee(id);
    }

    /**
     * CachePut:既调用方法,又更新缓存数据
     *
     * @param employee
     * @return
     */
    @CachePut(key = "#employee.id")
    public Employee updateEmployee(Employee employee) {
        System.out.println("---> updateEmployee" + employee);
        employeeMapper.updateEmp(employee);
        return employee;
    }


    @CacheEvict(key = "#id")
    public void deleteEmployee(Integer id) {
        System.out.println("--->删除employee的id是:" + id);
    }



}

ps: 1. 需要缓存的数据对象需要实现,Serializable接口,以便于json序列化存入redis

2. pom.xml引入


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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值