SpringBoot配置RedisTemplate和RedisCacheManager

import com.dxy.cache.pojo.Dept;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.*;

import java.net.UnknownHostException;

@Configuration
public class MyRedisConfig {


    /**
     * 往容器中添加RedisTemplate对象,设置序列化方式
     * @param redisConnectionFactory
     * @return
     * @throws UnknownHostException
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) throws UnknownHostException {
        RedisTemplate<String, Object> template = new RedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(valueSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(valueSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 往容器中添加RedisCacheManager容器,并设置序列化方式
     * @param redisConnectionFactory
     * @return
     */
    @Bean
    public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()));
        redisCacheConfiguration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
        return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
    }

//    private final CacheProperties cacheProperties;
//
//    MyRedisConfig(CacheProperties cacheProperties) {
//              this.cacheProperties = cacheProperties;
//    }

        /**
         * 往容器中添加org.springframework.data.redis.cache.RedisCacheConfiguration 对象
         * 目的是为了向默认的RedisCacheManager中设置属性,当然包括序列化
         * 如果仅仅是为了设置序列化方式可以和上面的配置二选一
         * 在RedisCacheManager内部使用org.springframework.data.redis.cache.RedisCacheConfiguration去保存相关配置信息
         */
//     @Bean
//     public org.springframework.data.redis.cache.RedisCacheConfiguration determineConfiguration() {
//               CacheProperties.Redis redisProperties = this.cacheProperties.getRedis();
//             org.springframework.data.redis.cache.RedisCacheConfiguration config = org.springframework.data.redis.cache.RedisCacheConfiguration
//                     .defaultCacheConfig();
//              config = config.serializeValuesWith(RedisSerializationContext.SerializationPair
//                                .fromSerializer(valueSerializer()));
//                if (redisProperties.getTimeToLive() != null) {
//                     config = config.entryTtl(redisProperties.getTimeToLive());
//                }
//                if (redisProperties.getKeyPrefix() != null) {
//                       config = config.prefixKeysWith(redisProperties.getKeyPrefix());
//                }if (!redisProperties.isCacheNullValues()) {
//                        config = config.disableCachingNullValues();
//                   }
//                if (!redisProperties.isUseKeyPrefix()) {
//                         config = config.disableKeyPrefix();
//                    }
//               return config;
//           }

            /**
              * 使用Jackson序列化器
               * @return
               */
            private RedisSerializer<Object> valueSerializer() {
                Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
                ObjectMapper objectMapper = new ObjectMapper();
                objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
                /**
                 * 这一句必须要,作用是序列化时将对象全类名一起保存下来
                 * 设置之后的序列化结果如下:
                 *  [
                 *   "com.dxy.cache.pojo.Dept",
                 *   {
                 *     "pid": 1,
                 *     "code": "11",
                 *     "name": "财务部1"
                 *   }
                 * ]
                 *
                 * 不设置的话,序列化结果如下,将无法反序列化
                 *
                 *  {
                 *     "pid": 1,
                 *     "code": "11",
                 *     "name": "财务部1"
                 *   }
                 */
//                objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
                //因为上面那句代码已经被标记成作废,因此用下面这个方法代替,仅仅测试了一下,不知道是否完全正确
                objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);
                serializer.setObjectMapper(objectMapper);
                return serializer;
             }


}
import com.dxy.cache.mapper.DeptMapper;
import com.dxy.cache.pojo.Dept;
import com.dxy.cache.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

@Service("deptService")
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    /**
     * @Cacheable 包含的属性
     *  cacheNames/value:缓存的名字
     *  key:支持SpEL表达式,#id=#a0=#p0=#root.args[0] 都是取出第一个参数的意思
     *     #result :可以取出返回值
     *  keyGenerator:key生成器,和key属性二选一
     *  cacheManager:缓存管理器,获取缓存的
     *  condition:条件,满足条件时才缓存,如#id>0
     *  unless:除非,当表达式为true时不缓存 ,如:#result == null
     *  sync:是否使用异步模式
     *
     *  缓存原理:
     *    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.SimpleCacheConfiguration
     *     org.springframework.boot.autoconfigure.cache.NoOpCacheConfiguration
     *   3、默认情况下,上面的配置类那个生效
     *   4、给容器中创建了一个CacheManager:ConcurrentMapCacheManager
     *   5、上述CacheManager可以创建和获取ConcurrentMapCache类型的缓存组件,它的作用是将数据存到ConcurrentMap中
     *
     *  运行流程:
     *   1、方法运行之前,去查询Cache(缓存组件),通过配置的cacheNames去查询,第一次会先创建该组件
     *   2、去Cache中查询缓存,通过key,默认key是方法参数,使用SimpleKeyGenerator生成key
     *      SimpleKeyGenerator生成key的策略:
     *           如果没有参数:key =  new SimpleKey()
     *           如果有一个参数:key = 参数的值
     *           如果有多个参数:key = new SimpleKey(多个参数)
     *   3、如果没有查询到缓存则调用目标方法
     *   4、将目标方法的返回值保存到缓存中
     *
     *
     * @param id
     * @return
     */
    @Cacheable(cacheNames="dept",key="#p0")
    @Override
    public Dept getDeptById(Long id) {
        System.out.println("发起数据库请求");
        return deptMapper.getDeptById(id);
    }

    @Override
    public int addDept(Dept dept) {
        return deptMapper.addDept(dept);
    }

    @Override
    /**
     * 更新缓存,在方法之后执行
     */
    @CachePut(cacheNames="dept",key="#p0.pid")
    public Dept updateDeptById(Dept dept) {
       deptMapper.updateDeptById(dept);
       return dept;
    }

    @Override
    /**
     * 删除缓存
     * 默认在方法执行之后进行缓存删除
     * 属性:
     *  allEntries=true 时表示删除cacheNames标识的缓存下的所有缓存,默认是false
     *  beforeInvocation=true 时表示在目标方法执行之前删除缓存,默认false
     */
    @CacheEvict(cacheNames = "dept",key = "#p0")
    public int delDept(Long id) {
        return deptMapper.delDept(id);
    }

    @Override
    /**
     * 组合@Cacheable、@CachePut、@CacheEvict的一个全面的注解
     */
    @Caching(
            cacheable = {
                    @Cacheable(cacheNames = "dept",key="#code")
            },
            put = {
                    @CachePut(cacheNames = "dept",key="#result.pid"),
                    @CachePut(cacheNames = "dept",key="#result.name"),
            }

//            ,
//            evict = {
//                    @CacheEvict(cacheNames = "dept",key="#code")
//            }
    )
    public Dept getDeptByCode(String code) {

        return deptMapper.getDeptByCode(code);
    }

}

 

  • 10
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
在Spring Boot中,使用yml格式配置远程Redis可以通过以下步骤实现: 1. 在pom.xml文件中添加Redis依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 在application.yml文件中添加Redis配置信息: ``` spring: redis: host: redis.example.com port: 6379 password: yourpassword ``` 其中,host为Redis服务器的IP地址或域名,port为Redis服务器的端口号,默认为6379,password为Redis服务器的密码,如果没有密码可以不填。 3. 在Redis配置类中进行配置: ``` @Configuration @EnableCaching public class RedisConfig extends CachingConfigurerSupport { @Value("${spring.redis.host}") private String host; @Value("${spring.redis.port}") private int port; @Value("${spring.redis.password}") private String password; @Bean public JedisPool redisPoolFactory() { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(8); jedisPoolConfig.setMaxTotal(8); jedisPoolConfig.setMinIdle(0); JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, 10000, password); return jedisPool; } @Bean public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(jedisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); redisTemplate.afterPropertiesSet(); return redisTemplate; } @Bean public RedisCacheManager cacheManager(JedisConnectionFactory jedisConnectionFactory) { RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .disableCachingNullValues() .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer())); RedisCacheManager redisCacheManager = RedisCacheManager.builder(jedisConnectionFactory) .cacheDefaults(redisCacheConfiguration) .build(); return redisCacheManager; } @Bean public JedisConnectionFactory jedisConnectionFactory() { JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(); jedisConnectionFactory.setHostName(host); jedisConnectionFactory.setPort(port); jedisConnectionFactory.setPassword(password); return jedisConnectionFactory; } } ``` 其中,注解@EnableCaching用于启用缓存功能,@Value用于从application.yml中读取Redis配置信息,redisPoolFactory方法用于创建Jedis连接池,redisTemplate方法用于创建RedisTemplate对象,cacheManager方法用于创建RedisCacheManager对象,jedisConnectionFactory方法用于创建JedisConnectionFactory对象。 4. 在需要使用Redis缓存的地方注入RedisTemplate对象即可: ``` @Autowired private RedisTemplate<String, Object> redisTemplate; ``` 以上就是使用yml格式配置远程Redis的步骤,使用Redis缓存可以提高数据查询的速度,降低数据库的压力。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值