springboot 配置redis

springboot配置redis

步骤: 配置rredis连接文件、配置redis键值文件、使用方法
这个redis配置文件显示的是中文缓存数据,

application.yml 配置文件
在这里插入图片描述

第一种配置文件

redis配置文件

package com.eaos.util.common;

import java.lang.reflect.Method;
import java.time.Duration;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.cache.CacheManager;
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.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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
public class RedisConfig extends CachingConfigurerSupport {
	@Bean
	public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
		return new RedisCacheManager(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory),
				this.getRedisCacheConfigurationWithTtl(30 * 60), // 默认策略,未配置的 key 会使用这个
				this.getRedisCacheConfigurationMap() // 指定 key 策略
		);
	}

	private Map<String, RedisCacheConfiguration> getRedisCacheConfigurationMap() {
		Map<String, RedisCacheConfiguration> redisCacheConfigurationMap = new HashMap<>();
		// SsoCache和BasicDataCache进行过期时间配置
		redisCacheConfigurationMap.put("SsoCache", this.getRedisCacheConfigurationWithTtl(24 * 60 * 60));
		redisCacheConfigurationMap.put("BasicDataCache", this.getRedisCacheConfigurationWithTtl(30 * 60));
		return redisCacheConfigurationMap;
	}

	private RedisCacheConfiguration getRedisCacheConfigurationWithTtl(Integer seconds) {
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
				Object.class);
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(om);

		RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig();
		redisCacheConfiguration = redisCacheConfiguration
				.serializeValuesWith(
						RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer))
				.entryTtl(Duration.ofSeconds(seconds));

		return redisCacheConfiguration;
	}

	@Bean
	public KeyGenerator wiselyKeyGenerator() {
		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());
				if (params == null || params.length == 0 || params[0] == null) {
					return null;
				}
				String join = String.join("&",
						Arrays.stream(params).map(Object::toString).collect(Collectors.toList()));
				String format = String.format("%s{%s}", sb.toString(), join);
				// log.info("缓存key:" + format);
				return format;
			}
		};
	}
}

使用方法

  1. 启动类添加 @EnableCaching //缓存注解
  2. 在service层或者dao层使用
在 service实现类上添加  @CacheConfig(cacheNames = "TbModuleService")
在方法上添加对应注解
	@Cacheable(keyGenerator="wiselyKeyGenerator") //查询
	@CachePut(keyGenerator = "wiselyKeyGenerator")//修改
	@CacheEvict(keyGenerator = "wiselyKeyGenerator")//删除

第二种配置文件

试用与mybatis文件 jpa可以自行尝试

package com.study.common;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

/**Redis缓存的通用配置类
  * 在mappers/*.xml中进行引用即可
 * redis工作的情况都我写入日志logger中,可以在控制台信息中进行跟踪查看
 * @author SMILE
 */
public class RedisCache implements Cache{
	private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
	
	private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    private String id; // cache instance id
    @SuppressWarnings("rawtypes")
	private RedisTemplate redisTemplate;

    private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis过期时间
    
    public RedisCache(String id) {
        if (id == null) {
            throw new IllegalArgumentException("Cache instances require an ID");
        }
        this.id = id;
    }

	@Override
    public String getId() {
        return id;
    }
	/**
     * Put query result to redis
     * @param key
     * @param value
     */
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public void putObject(Object key, Object value) {
    	try {
    		 RedisTemplate redisTemplate = getRedisTemplate();
             ValueOperations opsForValue = redisTemplate.opsForValue();
             opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
             logger.error("结果存入redis缓存中......"+key);
		} catch (Exception e) {
			 logger.error("结果存入redis缓存失败。。。。。。", e);
		}
    }

    /**
     * Get cached query result from redis
     *
     * @param key
     * @return
     */
    @SuppressWarnings({ "rawtypes"})
    @Override
    public Object getObject(Object key) {
        try {
        	 RedisTemplate redisTemplate = getRedisTemplate();
             ValueOperations opsForValue = redisTemplate.opsForValue();
             logger.error("成功从redis缓存中获取结果......"+key);
             return opsForValue.get(key);
        }
        catch (Throwable t) {
        	logger.error("获取结果到缓存失败。。。。。。", t);
            return null;
        }
    }

    /**
     * Remove cached query result from redis
     *
     * @param key
     * @return
     */
    @Override
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Object removeObject(Object key) {
        try {
            RedisTemplate redisTemplate = getRedisTemplate();
            redisTemplate.delete(key);
            logger.debug("缓存被删除了,......"+key);
        }
        catch (Throwable t) {
            logger.error("缓存删除failed。。。。。。", t);
        }
        return null;
    }

    /**
     * Clears this cache instance
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public void clear() {
    	RedisTemplate redisTemplate = getRedisTemplate();
        redisTemplate.execute((RedisCallback) connection -> {
            connection.flushDb();
            return null;
        });
        logger.debug("缓存被清空了.....");
    }

    /**
     * This method is not used
     *
     * @return
     */
    @Override
    public int getSize() {
        return 0;
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    @SuppressWarnings("rawtypes")
	private RedisTemplate getRedisTemplate() {
    	if (redisTemplate == null) {
    		//因为redis不是Spring的Bean对象,不受容器管理,不能使用Autoriwed
            redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
        }
        return redisTemplate;
    }
	
}

  • 使用方法
    在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值