spring boot 缓存详解(二)springboot + redis 缓存

引入pom 依赖


            org.springframework.boot
            spring-boot-starter-redis
            1.4.6.RELEASE
        

配置properties文件

# redis 配置
 ## mybatis 开启缓存
mybatis.configuration.cache-enabled=true
## redis相关
# Redis数据库索引(默认为0)
spring.redis.database=1
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=1000
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=2
# 连接超时时间(毫秒)
spring.redis.timeout=0

配置redisConfig文件

package com.example.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
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.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.lang.reflect.Method;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object target, Method method, Object... params) {
                StringBuilder sb = new StringBuilder();
                sb.append(target.getClass().getName());
                sb.append(method.getName());
                for (Object obj : params) {
                    sb.append(obj.toString());
                }
                return sb.toString();
            }
        };
    }
    /**
     * 申明缓存管理器,会创建一个切面(aspect)并触发Spring缓存注解的切点(pointcut)
     * 根据类或者方法所使用的注解以及缓存的状态,这个切面会从缓存中获取数据,将数据添加到缓存之中或者从缓存中移除某个值

     * @return
     */
    @Bean
    public RedisCacheManager cacheManager(RedisTemplate redisTemplate) {
        return new RedisCacheManager(redisTemplate);
    }


    @Bean
    @Primary
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        // 创建一个模板类
        RedisTemplate template = new RedisTemplate();
        // 将刚才的redis连接工厂设置到模板类中
        template.setConnectionFactory(factory);
        // 设置key的序列化器
        template.setKeySerializer(new StringRedisSerializer());
        // 设置value的序列化器
        //使用Jackson 2,将对象序列化为JSON
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        //json转对象类,不设置默认的会将json转成hashmap
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        template.setValueSerializer(jackson2JsonRedisSerializer);

        return template;
    }
}

service 等还用以前的

package com.example.service;

import com.example.dao.UserMapper;
import com.example.model.UserModel;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "userCache")
public class UserMapperService  {
    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Autowired
    UserMapper userMapper;
    @Cacheable(cacheNames = {"userCache"},key = "#id")
    public UserModel getUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @SuppressWarnings("SpringCacheableComponentsInspection")
    @Cacheable(cacheNames = {"userCache1"},keyGenerator = "nameKeyGenerator")
    public UserModel getUserById2(Integer id) {
        return userMapper.getUserById(id);
    }

    @CachePut(key = "#userModel.id",condition = "#userModel.id != null")
    public UserModel insertUser(UserModel userModel) {
        userMapper.insertUser(userModel);
        int id = userMapper.getCurrentIdSeq();
        userModel.setId(id);
        return userModel;
    }


    public void updateUserById(UserModel userModel) {
        userMapper.updateUserById(userModel);
    }

    @CacheEvict(value = "userCache1",key = "#id")
    public void deleteUserById(Integer id) {
        userMapper.deleteUserById(id);
    }
    @Cacheable(key = "#count")
    public Integer getUserInfoCount(String count){
        return userMapper.getCount();
    }
}

启动redis(必须,不然启动不了项目,或者在服务安装了redis)

spring boot 缓存详解(二)springboot + redis 缓存_第1张图片

测试略。。。

查看redisClient,已经有了缓存

spring boot 缓存详解(二)springboot + redis 缓存_第2张图片

特别注意

即使现在还配置了EhCache,在不指定的情况下,还用redis,系统不会使用EhCache.

done!!!

你可能感兴趣的:(spring,springboot,redis,redis,缓存,springboot)