springboot使用redis作为缓存

145 阅读2分钟

redis作为缓存使用

缓存:---存在内存中。

作用: ---提高查询性能,减少数据库访问频率。

什么样的数据适合放入缓存: ---安全系数低的。---访问频率高 ---修改频率低 。

原理:

image.png

实现缓存的步骤


@Service
public class DeptService {

    @Autowired
    private DeptDao deptDao;
    @Resource(name="myRedisTemplate")
    private RedisTemplate redisTemplate;

    public Dept findById(Integer id){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //1.查询缓存是否存在该数据
        Object o = valueOperations.get("dept:" + id);
        if(o!=null && o instanceof Dept){
            return (Dept) o;
        }
        //2.查询数据库
        Dept dept = deptDao.selectById(id);
        if(dept!=null) {
            //把该数据放入缓冲中
            valueOperations.set("dept:" + id, dept, 24, TimeUnit.HOURS);
        }
        return dept;
    }


    public Dept update(Dept dept){
         ValueOperations valueOperations = redisTemplate.opsForValue();
         //1.先改数据库还是先删缓冲。
         deptDao.updateById(dept);
         valueOperations.set("dept:"+dept.getId(),dept);
         return dept;
    }

    public Dept insert(Dept dept){
          deptDao.insert(dept);
          return dept;
    }

    public int delete(int id){
         redisTemplate.delete("dept:"+id);
         deptDao.deleteById(id);
         return 1;
    }
}

手写麻烦,这也是一些没有技术含量的重复性代码,所以springboot框架在1.3.0版本之后,给我们提供了缓存的注解,大大简化了开发。我们该如何配置?

(1)配置缓存配置

@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
    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);
    // 配置序列化(解决乱码的问题),过期时间600秒
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(600)) //缓存过期10分钟 ---- 业务需求。
            .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer))//设置key的序列化方式
            .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)) //设置value的序列化
            .disableCachingNullValues();
    RedisCacheManager cacheManager = RedisCacheManager.builder(factory)
            .cacheDefaults(config)
            .build();
    return cacheManager;
}

(2)开启缓存注解

可以加载springboot主启动类上,也可以加在缓存配置类上

image.png

image.png

(3)使用缓存注解

package com.cjj.service;

import com.cjj.dao.StudentDao;
import com.cjj.entity.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
public class StudentService {

    @Autowired
    private StudentDao studentDao;

    //使用于查询的缓存注解: 缓存的名称叫做: cacheNames::key  todo 查询专用缓存注解
    //先从缓存中找名字叫:cacheNames::key 如果存在,则方法不执行。如果不存在会执行方法,并把改方法的返回值作为缓存的值.
    //必须开启缓存注解驱动
    @Cacheable(cacheNames = "student",key="#id")
    public Student findById(Integer id){
        Student dept = studentDao.selectById(id);
        return dept;
    }

    //先执行方法体,并把方法的返回结果作为缓存的值。修改缓存的值。 todo 修改专用缓存注解
    @CachePut(cacheNames = "student",key="#student.id")
    public Student update(Student student){
        //1.先该数据库还是先删缓冲。
        studentDao.updateById(student);
        return student;
    }

    //删除缓存再执行方法体, todo 删除专用缓存注解
    @CacheEvict(cacheNames = "student",key = "#id")
    public int delete(int id){
        studentDao.deleteById(id);
        return 1;
    }
}

(4)测试

image.png