springboot与缓存

作者: 老奶猹 | 来源:发表于2020-05-08 18:27 被阅读0次

问题一:使用缓存步骤


  一、搭建基本环境
  1.导入数据库文件,创建出department和employee表
  2.创建javaBean封装数据
  3.整合mybatis操作数据库
      1.配置数据源信息
      2.使用注解版MyBatis:
         1)@MapperScan指定要扫描的mapper接口所在的包
  二、快速体验缓存
     步骤:
        1.开启基于注解的缓存 @EnableCaching
        2.在要缓存结果的方法上添加缓存注解
        @Cacheable
        @CacheEvict
        @CachePut
  默认使用的是ConcurrentMapCacheManage==ConcurrentMapCache:将数据保存在CurrentMap
  开发中使用的缓存中间件redis、memcached、ehcache;
  三、整合redis作为缓存
  Redis是一个开源(BSD许可)的,内存中的数据结构存储系统,它可以用做数据库、缓存和消息中间件。
   1.安装redis:使用docker
   2.引入redis的starter
   3.配置redis
   4.测试缓存
      原理:CacheManager==Cache 缓存组件来实际给缓存中存取数据
       1)、引入redis的starter,容器中保存的是RedisCacheManager;
       2)、RedisCacheManager帮我们创建RedisCache来作为缓存组件;RedisCache通过操作缓存数据的
        3)、默认保存数据 k-v 都是Objet;利用序列化保存;那么如何保存为json?
               1.引入了redis的start、cacheManager变为RedisCacheManager;
               2.默认创建的RedisCacheManager操作redis时使用的是RedisTemplate(Object,Object)
               3.RedisTemplate<Object,Object> 是默认使用jdk的序列化机制
        4)、自定义CacheManager

问题二:常用的缓存注解介绍

/**
 * @CacheConfig 缓存公共配置,对整个类中的缓存进行配置
 */
@CacheConfig(cacheNames = "emp")
@Service
public class EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    /**
     * 将方法的运行结果进行缓存;以后再要相同的数据,直接从缓存中获取,不用调用方法
     *
     * CacheManager管理多个Cache组件,对缓存的真正CRUD操作在Cache组件中,每一个缓存组件有自己唯一一个名字
     * 几个属性:
     *        cacheNames/value:指定缓存组件的名字
     *        key:缓存数据使用的key:可以用它来指定。默认使用方法参数的值 如:1-方法的返回值
     *        keyGenerator:key的生成器:可以自己指定key的生成器的组件id
     *                   key/keyGenerator,二选一使用
     *        cacheeManager:指定缓存管理器,或者cacheResolver指定获取解析器
     *        condition:指定符合条件的情况下才缓存
     *                condition = "#id>0"
     *        unless:否定缓存:当unless指定的条件为true,方法的返回值就不会被缓存,可以获取到结果进行判断
     *                 unless = "#result == null"
     *        sync:是否使用异步模式
     * @param id
     * @return
     */

    @Cacheable(cacheNames = {"emp"}/*,cacheManager = "myKeyGenerator"*/)
    public Employee getEmp(Integer id){
        System.out.println("查询"+id+"号员工");
        Employee emp = employeeMapper.getEmpById(id);
        return emp;
    }

    /**
     * @CachePut,既调用方法,又更新缓存数据,同步更新缓存
     * 修改了数据库的某个数据,同时更新缓存;
     * 运行时机:
     *    1.先调用目标方法
     *    2.将目标方法的结果缓存起来
     *
     * 测试步骤:
     *   1.查询1号员工,查到的结果会放在缓存中;
     *          key:1   value:  lastname:张三
     *   2.以后查询还是之前的结果
     *   3.更新1号员工:[lastName: zhangsan; gender:0]
     *           将方法的返回值也放进缓存了;
     *           key:传入的employee对象  值:方法返回的employee对象
     *   4.查询1号员工?
     *      应该是更新后的员工:
     *         key = "#employee.id":使用传入的参数的员工id;
     *                   or
     *         key = "#result.id": 使用返回后的id
     *      为什么缓存中是没更新前的信息?【1号员工没有再缓存中更新】
     */
    @CachePut(/*value = "emp",*/key = "#employee.id")
    public Employee updateEmp(Employee employee){
        System.out.println("updateEmp:"+employee);
        employeeMapper.updateEmp(employee);
        return employee;
    }

    /**
     * @CacheEvict: 缓存清除
     * key: 指定要清除的数据
     * allEntries = true:清除指定value这个缓存中的所有数据
     * beforeInvocation = false; 缓存的清除是否在方法执行之前,默认为false;
     *      如果为true代表缓存清除在方法执行之前执行,也就是说无论方法执行是否出现异常,都先清除缓存
     */

    @CacheEvict(/*value = "emp",key = "#id",allEntries = true,beforeInvocation = true*/)
    public void deleteEmp(Integer id){
        System.out.println("deleteEmp"+id);
//        employeeMapper.deleteEmpById(id);
    }

    /**
     * 若想在一个方法上实现复杂条件缓存,可以用@Caching注解
     */
    @Caching(
            cacheable = {
                    @Cacheable(/*value = "emp",*/key = "#lastName")
            },
            put = {
                    @CachePut(/*value = "emp",*/key = "#result.id"),
                    @CachePut(/*value = "emp",*/key = "#result.email")
            }
    )
    public Employee getEmpByLastName(String lastName){
        return employeeMapper.getEmpByLastName(lastName);
    }

问题三:springboot与redis

springboot要想使用redis,需要先导入依赖

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

        <!-- jackson序列化 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
        </dependency>

并在主配置文件中连接redis

spring.redis.host=192.168.0.113

单元测试:

@SpringBootTest
class Springboot001CacheApplicationTests {
    @Autowired
    EmployeeMapper employeeMapper;
    @Autowired
    StringRedisTemplate stringRedisTemplate; //操作k-v都是字符串
    @Autowired
    RedisTemplate redisTemplate; //k-v都是对象
    @Autowired
    RedisTemplate<Object,Employee> empRedisTemplate;

    @Test
    void contextLoads() {
        Employee employee01 = employeeMapper.getEmpById(1);
        System.out.println(employee01);
    }

    @Test
    public void test01(){
        //stringRedisTemplate.opsForValue().append("msg","hello"); //给redis保存一个数据
        //String msg = stringRedisTemplate.opsForValue().get("msg");
        //System.out.println(msg);

        //stringRedisTemplate.opsForList().leftPush("mylist","1"); //向一个数组中存值
        //stringRedisTemplate.opsForList().leftPush("mylist","2");
        //stringRedisTemplate.opsForList().leftPop("mylist");  取值
    }

    //测试保存对象
    @Test
    public void test02(){
        Employee employee01 = employeeMapper.getEmpById(1);
        //默认如果保存对象,使用jdk序列化机制,序列化后的数据保存到redis中
        redisTemplate.opsForValue().set("emp-01",employee01);
        //1.将数据以json的方式保存
        //(1)自己将对象转化为json
        //(2)redisTemplate默认的序列化规则,改变默认的序列化规则
        empRedisTemplate.opsForValue().set("emp-01",employee01);
    }

}

自定义配置类,重新RedisTemplate方法

@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate<Object, Employee> empRedisTemplate(RedisConnectionFactory redisConnectionFactory)
        throws UnknownHostException{
        RedisTemplate<Object,Employee> template = new RedisTemplate<Object, Employee>();
        template.setConnectionFactory(redisConnectionFactory);
        // 使用Jackson2JsonRedisSerialize 替换默认的jdkSerializeable序列化
        Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }
}

问题四:改变springboot缓存序列化方式

springboot默认的序列化方式为jdk序列化方式,若想采用json序列化方式需要进行自定义配置
因为我所学习的视频是雷丰阳大神讲解的springboot1.5版本,而现在已经普遍学习使用springboot2.X版本,所以在自定义设置json序列化的方式和雷神讲的方式有很大的不同。
springboot2.X版本的缓存自定义配置类进行如下配置:
重写RedisCacheManager方法:

@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);
    }

}
图片.png

相关文章