Java - 采用redis缓存数据[redis客户端开发]

2 篇文章 0 订阅

pom.xml依赖:

<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-redis</artifactId>
			<version>1.8.6.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>biz.paluch.redis</groupId>
			<artifactId>lettuce</artifactId>
			<version>4.4.0.Final</version>
		</dependency>

代码:

import org.springframework.cache.CacheManager;
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.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 自定义缓存机制
 * @author ray.sun
 *
 */
@Configuration
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory cf) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setConnectionFactory(cf);
        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        
        //设置默认过期时间,单位秒,此处设置为1天
        cacheManager.setDefaultExpiration(3600 * 24);
        
        return cacheManager;
    }
}

#############################################
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Service;

/**
 * 
 * @author ray.sun
 *
 */
@Service
public class RedisCacheFlusher implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    private RedisConnectionFactory connFactory;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        Set<byte[]> keys = connFactory.getConnection().keys(RedisCacheKeyGenerator.PREFIX_PATTERN.getBytes());
        keys.forEach(e -> {
            connFactory.getConnection().del(e);
        });
    }

}

#######################################
import java.lang.reflect.Method;

import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.cache.interceptor.SimpleKeyGenerator;
import org.springframework.stereotype.Service;

/**
 * 该类用来生成缓存的key, 重写方法generate, 定义适合业务需要的key
 * @author ray.sun
 *
 */
@Service
public class RedisCacheKeyGenerator implements KeyGenerator {

    private static final String PREFIX = "AppName_";

    public static final String PREFIX_PATTERN = "*AppName*";
    
    public static final String EMPTY = "";

    @SuppressWarnings("rawtypes")
    @Override
    public Object generate(Object target, Method method, Object... params) {
        // get class name
        Class[] interfaces = target.getClass().getInterfaces();
        String className;
        if (interfaces == null || interfaces.length == 0) {
            className = target.getClass().getSimpleName();
        } else {
            className = interfaces[0].getSimpleName();
        }
        // get parameter value
        String paramValue;
        if (params.length == 0) {
            paramValue = EMPTY;
        } else {
            paramValue = SimpleKeyGenerator.generateKey(params).toString();
        }

        StringBuilder sb = new StringBuilder(PREFIX);
        sb.append(className).append(method.getName()).append(paramValue);
        return sb.toString();
    }

}

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.session.data.redis.config.ConfigureRedisAction;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;

/**
 * 该类用于定义redis server端参数
 * @author ray.sun
 *
 */
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)
public class RedisConfig {
	
	@Value("${redis.masterName}")
	private String masterName;
	
	@Value("${redis.sentinels}")
	private String[] sentinels;
	
	@Value("${redis.databaseIndex}")
	private int redisDb;

    @Bean
    public RedisConnectionFactory connectionFactory() {
        
        Set<String> sentinelHostAndPorts = new HashSet<String>();
        
        for (String sentinel : sentinels) {
            sentinelHostAndPorts.add(sentinel);
        }
        RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration(masterName, sentinelHostAndPorts);
        LettuceConnectionFactory redisFactory = new LettuceConnectionFactory(sentinelConfig);
        redisFactory.setDatabase(redisDb);
        return redisFactory;
    }

    @Bean
    public static ConfigureRedisAction configureRedisAction() {
        return ConfigureRedisAction.NO_OP;
    }

}

//给服务层添加缓存
@Cacheable(value = "自定义缓存名字", 
			keyGenerator = "redisCacheKeyGenerator",  //该值与前面定义的service 类RedisCacheKeyGenerator的名字一致,只是首字母小写了
			unless="#result.attr1 == null")	//定义不需要缓存的情况,unless可选
public Province getProvince(String provinceName, Date date){
	...
}

//也可以给持久层添加缓存,方法相同	

...





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值