SpringBoot 用Redis 缓存

 

SpringBoot使用Redis缓存

    现在网上教程的大部分是springboot1.x的一些redis设置。现在SpringBoot2.x 中RedisCacheManager 的构造方法发生改变,教程视频中的设置已经行不通。  经过努力下面的MyRedisConfig亲测行得通 = =。

(1)引入jar包,

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

(2)修改项目启动类,增加注解@EnableCaching,开启缓存功能,(要扫描mapper的话也要@MapperScan

package com.***;

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

@SpringBootApplication
@EnableCaching
public class SpringbootCacheApplication {

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

(3)application.properties中配置Redis连接信息,(最简易写,有需求可添加其他配置设置)

spring.redis.host  指定好redis作用主机ip

spring.datasource.url=jdbc:mysql://localhost:3306/springboot
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=******

#开启驼峰命名
mybatis.configuration.map-underscore-to-camel-case=true
#打印SQL语句
logging.level.com.ysp.mapper=debug
debug=true

spring.redis.host=192.168.0.113

(4)Mapper和控制器和没什么改变 。 下面是service层用注解俩缓存:

package com.***.service.impl;

import com.ysp.mapper.EmployeeMapper;
import com.ysp.model.Employee;
import com.ysp.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.*;
import org.springframework.stereotype.Service;

@CacheConfig(cacheNames = "emp")
@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    EmployeeMapper employeeMapper;

    @Cacheable(value = {"emp"})
    @Override
    public Employee getEmpById(Integer id) {
        System.out.println("查询到"+id+"号员工");
        Employee emp = employeeMapper.getEmpById(id);
        return emp;
    }

    @Override
    public int insertEmp(Employee employee) {
        return employeeMapper.insertEmp(employee);
    }

    @CachePut(key = "#result.id")
    @Override
    public Employee updateEmp(Employee employee) {
        System.out.println("更新了:"+employee);
        employeeMapper.updateEmp(employee);
        return employee;
    }


    @CacheEvict(key = "#id",beforeInvocation = true)
    //beforeInvocation -- 方法之后执行 默认值为false
    @Override
    public int deleteEmp(Integer id) {
//        employeeMapper.deleteEmp(id);
        System.out.println("删除了"+id+"号员工");
        return 1;
    }

    @Caching(
            cacheable = {
                    @Cacheable(key = "#lastName")
            },
            put = {
                    @CachePut(key = "#result.id"),
                    @CachePut(key = "#result.email")
            }
    )
    @Override
    public Employee getEmpByLastName(String lastName){
        System.out.println("查询了:"+lastName);
        return employeeMapper.getEmpByLastName(lastName);
    }
}

       @Cacheable将查询结果缓存到redis中,(key="#p0")指定传入的第一个参数作为redis的key。

  @CachePut,指定key,将更新的结果同步到redis中

  @CacheEvict,指定key,删除指定缓存数据,allEntries=true,方法调用后将立即清除全部缓存

       @Caching , 可自行定义缓存

(5)自定义一个MyRedisConfig

package com.***.config;


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class MyRedisConfig extends CachingConfigurerSupport {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        //创建JSON格式的序列化
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);

        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        serializer.setObjectMapper(objectMapper);
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(serializer);
        //设置序列化
        redisTemplate.setValueSerializer(serializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    public RedisCacheManager redisCacheManager(RedisTemplate redisTemplate) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisTemplate.getConnectionFactory());
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisTemplate.getValueSerializer()));
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }


}

1、第一次运行控制台会打印相应sql,说明数据是去控制器拿的。

2、当刷新页面第二次获取数据时,控制台不打印sql,且还是获得数据。说明是从缓存中获取的

这时查看redis中有相应的key。

如若有错误地方,请指出。本人菜鸡--

猜你喜欢

转载自blog.csdn.net/baidu_41741410/article/details/81780855