前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springBoot 缓存开发

springBoot 缓存开发

作者头像
用户5927264
发布2019-08-01 10:58:10
3650
发布2019-08-01 10:58:10
举报
文章被收录于专栏:OSChinaOSChina
代码语言:javascript
复制
package catchManager;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

/**
 *
 * 一、搭建基本环境
 * 1、导入数据库文件 创建出department和employee表
 * 2、创建javaBean封装数据
 * 3、整合MyBatis操作数据库
 * 		1.配置数据源信息
 * 		2.使用注解版的MyBatis;
 * 			1)、@MapperScan指定需要扫描的mapper接口所在的包
 * 二、快速体验缓存
 * 		步骤:
 * 			1、开启基于注解的缓存 @EnableCaching
 * 			2、标注缓存注解即可
 * 				@Cacheable
 * 				@CacheEvict
 * 				@CachePut
 * 		默认使用的是ConcurrentMapCacheManager==ConcurrentMapCache;将数据保存在	ConcurrentMap<Object, Object>中
 * 		开发中使用缓存中间件;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通过操作redis缓存数据的
 *		3)、默认保存数据 k-v 都是Object;利用序列化保存;如何保存为json
 *   			1、引入了redis的starter,cacheManager变为 RedisCacheManager;
 *   			2、默认创建的 RedisCacheManager 操作redis的时候使用的是 RedisTemplate<Object, Object>
 *   			3、RedisTemplate<Object, Object> 是 默认使用jdk的序列化机制
 *      4)、自定义CacheManager;
 *
 */
@SpringBootApplication
@MapperScan("catchManager/dao")
@EnableCaching
public class CatchApplication {

	public static void main(String[] args) {
		SpringApplication.run(CatchApplication.class, args);
	}
}
代码语言:javascript
复制
package catchManager.service;

import catchManager.dao.EmployeeMapper;
import catchManager.model.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

@CacheConfig(cacheNames = "emp")//抽取缓存中的公共配置
@Service
public class EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * @Cacheable
     * 讲方法的运行结果进行缓存,以后再有相同的数据,直接从缓存中获取,不用调用方法
     *
     * cacheManager 管理多个cache组件的,对缓存的真正crud操作在cache组件中,每一个缓存组件有自己唯一一个名字
     * 几个属性:
     *        cacheNames/value:指定缓存组价的名字;
     *        key :缓存数据使用的key;可以用它来指定。默认是使用方法参数的值  1-方法的返回值
     *              key = "#root.methodName+'['+#id+']'"    : key = selectById[1]
     *
     *        keyGenerator: key的生成器;可以自己指定key的生成器的组件id
     *              key/keyGenerator : 二选一使用
     *        cacheManager :指定缓存管理器;  或者 cacheResolver 指定获取解析器
     *        condition :指定符合条件的情况下才缓存 condition = "#id>0"
     *                  condition = "#a0>1"  : 当一个参数大于1的时候才进行缓存
     *        unless:否定缓存,在条件成立的情况下,方法的返回值不会被缓存,可以获取到结果进行判断
     *              unless = "#result == null "  : 当结果= null的时候 不缓存
     *        sync: 是否使用异步模式(该模式下 unless 将不支持了)
     *
     *
     *
     * 原理:
     *   1、自动配置类;CacheAutoConfiguration
     *   2、缓存的配置类
     *   org.springframework.boot.autoconfigure.cache.GenericCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.JCacheCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.EhCacheCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.HazelcastCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.InfinispanCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.CouchbaseCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.RedisCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.CaffeineCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.GuavaCacheConfiguration
     *   org.springframework.boot.autoconfigure.cache.SimpleCacheConfiguration【默认】
     *   org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
     *   3、哪个配置类默认生效:SimpleCacheConfiguration;
     *
     *   4、给容器中注册了一个CacheManager:ConcurrentMapCacheManager
     *   5、可以获取和创建ConcurrentMapCache类型的缓存组件;他的作用将数据保存在ConcurrentMap中;
     *
     *   运行流程:
     *   @Cacheable:
     *   1、方法运行之前,先去查询Cache(缓存组件),按照cacheNames指定的名字获取;
     *      (CacheManager先获取相应的缓存),第一次获取缓存如果没有Cache组件会自动创建。
     *   2、去Cache中查找缓存的内容,使用一个key,默认就是方法的参数;
     *      key是按照某种策略生成的;默认是使用keyGenerator生成的,默认使用SimpleKeyGenerator生成key;
     *          SimpleKeyGenerator生成key的默认策略;
     *                  如果没有参数;key=new SimpleKey();
     *                  如果有一个参数:key=参数的值
     *                  如果有多个参数:key=new SimpleKey(params);
     *   3、没有查到缓存就调用目标方法;
     *   4、将目标方法返回的结果,放进缓存中
     *
     *   @Cacheable标注的方法执行之前先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
     *   如果没有就运行方法并将结果放入缓存;以后再来调用就可以直接使用缓存中的数据;
     *
     *   核心:
     *      1)、使用CacheManager【ConcurrentMapCacheManager】按照名字得到Cache【ConcurrentMapCache】组件
     *      2)、key使用keyGenerator生成的,默认是SimpleKeyGenerator
     * @param id
     * @return
     */
    @Cacheable(cacheNames = {"emp"})
    public Employee selectById(Integer id){
        System.out.println("查询第"+id+"号员工的信息");
        Employee e =  employeeMapper.getEmpById(id);
        return  e;
    }

    /**
     * @CachePut  即调用方法,又更新缓存中的数据( 一定要和 @Cacheable中的key保持一致)
     * 运行时机:
     *      1.先调用目标方法,
     *      2.在将方法的结果保存到缓存中
     *
     * 测试步骤
     *      1.先查询1号员工,查到的结果放到缓存中
     *      2.以后查询还有之前的结果
     *      3.更新1号员工的信息
     *      4.查询到1号员工?
     *             查询到的还是跟新之前的1号员工。。。。。为什么? 因为没有指定key值默认是以参数名称绑定数据的
     *             解决办法: 指定key 和查询时使用的key保持一致
     *
     * @param emp
     * @return
     */
    @CachePut(value = "emp",key = "#emp.id")
    public Employee updateById(Employee emp){
        System.out.println("跟新了员工信息"+emp.getId());
        employeeMapper.updateEmp(emp);
        return emp;
    }

    /**
     * @CacheEvict :清空缓存
     *      value = "emp"  缓存的名字
     *      key = "#id"   缓存的id
     *      allEntries = true  指定清空这个缓存中的所有数据
     *      beforeInvocation = true 再方法调用之前清除缓存,(默认是false)
     * @param id
     */
    @CacheEvict(value = "emp" ,key = "#id" ,allEntries = true,beforeInvocation = true)
    public void deleteEmp(Integer id){
        System.out.println("删除" + 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);
    }
}

自定义缓存管理器

代码语言:javascript
复制
package catchManager.cofig;

import catchManager.model.Employee;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.net.UnknownHostException;

/**
 * 我们的redis的配置类
 */
@Configuration
public class MyRedisConfig {

    @Bean
    public RedisTemplate<Object, Employee> MyRedisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Employee.class);
        template.setDefaultSerializer(serializer);
        return template;
    }

    //CacheManagerCustomizers可以来定制缓存的一些规则
    @Primary  //将某个缓存管理器作为默认的
    @Bean
    public RedisCacheManager employeeCacheManager(RedisTemplate<Object, Employee> empRedisTemplate){
        RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
        //key多了一个前缀

        //使用前缀,默认会将CacheName作为key的前缀
        cacheManager.setUsePrefix(true);
        return cacheManager;
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 Redis
腾讯云数据库 Redis(TencentDB for Redis)是腾讯云打造的兼容 Redis 协议的缓存和存储服务。丰富的数据结构能帮助您完成不同类型的业务场景开发。支持主从热备,提供自动容灾切换、数据备份、故障迁移、实例监控、在线扩容、数据回档等全套的数据库服务。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档