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.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </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<Object, Employee> empRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Employee> template = new RedisTemplate<Object, Employee>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Employee> ser = new Jackson2JsonRedisSerializer<Employee>(Employee.class);
        template.setDefaultSerializer(ser);
        return template;
    }
    //自定义deptRedisTemplate
    @Bean
    public RedisTemplate<Object, Department> deptRedisTemplate(
            RedisConnectionFactory redisConnectionFactory)
            throws UnknownHostException {
        RedisTemplate<Object, Department> template = new RedisTemplate<Object, Department>();
        template.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer<Department> ser = new Jackson2JsonRedisSerializer<Department>(Department.class);
        template.setDefaultSerializer(ser);
        return template;
    }



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

    @Bean
    public RedisCacheManager deptCacheManager(RedisTemplate<Object, Department> 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将开启缓存

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值