SpringBoot使用SpringCache并整合Redis的CRUD

使用docker安装redis

docker pull redis
docker run -d -p 6379:6379 --name redis01 镜像ID

在pom.xml中引入依赖,引入SpringCache和Redis


        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-cacheartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>

在application.properties中配置mysql,mybatis,redis

spring.datasource.url=jdbc:mysql://130.733.243.104:3307/springboot?useSSL=true&verifyServerCertificate=false&allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=lhc123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

mybatis.configuration.map-underscore-to-camel-case=true
logging.level.com.lhc.dao=debug

spring.redis.host=120.77.245.104
spring.redis.port=6379

启动缓存注解及mybatis的注解版的mapper扫描


@EnableCaching
@ManagedBean("com.lhc.dao")
@SpringBootApplication
public class Cache2Application {

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

配置序列化为jackson2序列化,而不是jdk的序列化,需要定制,我的数据库使用经常用来做测试的employee和department


@Configuration
public class MyRedisConfig {


    //自定义empRedisTemplate
    @Bean
    public RedisTemplate empRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer ser = new Jackson2JsonRedisSerializer(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }
    //自定义deptRedisTemplate
    @Bean
    public RedisTemplate deptRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer ser = new Jackson2JsonRedisSerializer(Department.class);
        template.setDefaultSerializer(ser);
        return template;
    }



    //定义多个RedisCacheManager,需要使用@Primary确定默认RedisCacheManager
    @Primary
    @Bean
    public RedisCacheManager employeeCacheManager(RedisTemplate empRedisTemplate){
        RedisCacheManager cacheManager = new RedisCacheManager(empRedisTemplate);
        //使用前缀,默认会将CacheName作为key的前缀
        cacheManager.setUsePrefix(true);
        return cacheManager;
    }

    @Bean
    public RedisCacheManager deptCacheManager(RedisTemplate deptRedisTemplate){
        RedisCacheManager cacheManager = new RedisCacheManager(deptRedisTemplate);
        //使用前缀,默认会将CacheName作为key的前缀
        cacheManager.setUsePrefix(true);
        return cacheManager;
    }


}

dao使用mybatis的注解版,较为简单,跳过,看一下service
在service中配置使用缓存


//不注明cacheManager默认为@primary的cacheManger
//抽取缓存的公共配置
@CacheConfig(cacheNames="emp",cacheManager = "employeeCacheManager")
@Service
public class EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    //查询,使用缓存
    @Cacheable(cacheNames = "emp",key = "#id")
    public Employee getEmp(Integer id){
        System.out.println("查询"+id+"号员工");
        Employee emp = employeeMapper.getEmpById(id);
        return emp;
    }

    //更新,修改缓存
    @CachePut(key = "#result.id")
    public Employee updateEmp(Employee employee){
        System.out.println("updateEmp:"+employee);
        employeeMapper.updateEmp(employee);
        return employee;
    }

    //删除,删除缓存
    //beforeInvocation=true,防止执行过程中出现异常
    @CacheEvict(beforeInvocation = true ,key = "#id")
    public void deleteEmp(Integer id){
        System.out.println("deleteEmp:"+id);
        //employeeMapper.deleteEmpById(id);
    }

    // @Caching 定义复杂的缓存规则
    @Caching(
         cacheable = {
             @Cacheable(key = "#lastName")
         },
         put = {
             @CachePut(key = "#result.id"),
             @CachePut(key = "#result.email")
         }
    )
    public Employee getEmpByLastName(String lastName){
        return employeeMapper.getEmpByLastName(lastName);
    }

}

于是在controller中调用这些service将开启缓存

你可能感兴趣的:(SpringBoot,Redis)