博客
关于我
封装RedisUtils,静态调用超级简单。【xdxFramework】
阅读量:170 次
发布时间:2019-02-28

本文共 12141 字,大约阅读时间需要 40 分钟。

Redis 封装与使用说明

项目截图

图片描述已移除

代码

RedisConfig

import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.springframework.beans.factory.annotation.Value;import org.springframework.cache.CacheManager;import org.springframework.cache.annotation.CachingConfigurerSupport;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.connection.RedisPassword;import org.springframework.data.redis.connection.RedisStandaloneConfiguration;import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;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 redis.clients.jedis.JedisPoolConfig;import java.lang.reflect.Method;import java.time.Duration;@Configuration@EnableCachingpublic class RedisConfig extends CachingConfigurerSupport {    @Value("${spring.redis.jedis.pool.max-idle}")    private Integer maxIdle;    @Value("${spring.redis.jedis.pool.min-idle}")    private Integer minIdle;    @Value("${spring.redis.jedis.pool.max-active}")    private Integer maxActive;    @Value("${spring.redis.jedis.pool.min-idle}")    private Integer maxWait;    @Value("${spring.redis.host}")    private String host;    @Value("${spring.redis.port}")    private Integer port;    @Value("${spring.redis.database}")    private Integer database;    @Value("${spring.redis.password}")    private String password;    @Value("${spring.redis.timeout}")    private Integer timeout;    @Bean    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {        RedisCacheManager manager = RedisCacheManager.create(connectionFactory);        return manager;    }    @Bean    public JedisPoolConfig jedisPoolConfig() {        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();        jedisPoolConfig.setMaxIdle(maxIdle);        jedisPoolConfig.setMinIdle(minIdle);        jedisPoolConfig.setMaxTotal(maxActive);        jedisPoolConfig.setMaxWaitMillis(maxWait);        jedisPoolConfig.setTestWhileIdle(true);        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);        jedisPoolConfig.setNumTestsPerEvictionRun(10);        jedisPoolConfig.setMinEvictableIdleTimeMillis(60000);        jedisPoolConfig.setTestOnBorrow(true);        jedisPoolConfig.setTestOnReturn(true);        return jedisPoolConfig;    }    @Bean    public JedisConnectionFactory connectionFactory(JedisPoolConfig jedisPoolConfig) {        String host = this.host;        Integer port = this.port;        Integer database = this.database;        String password = this.password;        Integer timeout = this.timeout;        RedisStandaloneConfiguration rf = new RedisStandaloneConfiguration();        rf.setHostName(host);        rf.setPort(port);        rf.setDatabase(database);        rf.setPassword(RedisPassword.of(password));        JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpb = jedisClientConfiguration.usePooling();        jpb.poolConfig(jedisPoolConfig);        jedisClientConfiguration.connectTimeout(Duration.ofMillis(timeout));        JedisConnectionFactory factory = new JedisConnectionFactory(rf, jedisClientConfiguration.build());        return factory;    }    @Bean    @Override    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();            }        };    }    @Bean    public RedisTemplate
redisTemplate(RedisConnectionFactory factory) { RedisTemplate
template = new RedisTemplate<>(); template.setConnectionFactory(factory); Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(mapper); template.setValueSerializer(serializer); template.setKeySerializer(new StringRedisSerializer()); template.afterPropertiesSet(); return template; }}

CacheContext

import java.lang.reflect.ParameterizedType;import java.lang.reflect.Type;import java.util.concurrent.TimeUnit;public class CacheContext
{ static CacheManager cache; @SuppressWarnings("unchecked") public void init() { Type type = this.getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { Class
entityClass = (Class
) ((ParameterizedType) type).getActualTypeArguments()[0]; try { cache = entityClass.newInstance(); cache.init(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } } public static void remove(final String... keys) { cache.remove(keys); } public static boolean remove(final String key) { return cache.remove(key); } public static boolean exists(final String key) { return cache.exists(key); } public static Object get(final String key) { return cache.get(key); } public static boolean set(final String key, Object value) { return cache.set(key, value); } public static boolean set(final String key, Object value, long expireTime) { return cache.set(key, value, expireTime); } public static Boolean expire(final String key, final long timeout) { return cache.expire(key, timeout); } public static Boolean expire(final String key, final long timeout, final TimeUnit unit) { return cache.expire(key, timeout, unit); } public static Long getExpire(final String key) { return cache.getExpire(key); }}

CacheManager

import java.util.concurrent.TimeUnit;public interface CacheManager {    Long defaultExpirationTime = 30L;    void init();    void remove(final String... keys);    boolean remove(final String key);    boolean exists(final String key);    Object get(final String key);    boolean set(final String key, Object value);    boolean set(final String key, Object value, long expireTime);    Boolean expire(final String key, final long timeout);    Boolean expire(final String key, final long timeout, final TimeUnit unit);    Long getExpire(final String key);}

RedisManager

import com.xdx97.framework.utils.SpringContextUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Component;import javax.annotation.Resource;import java.io.Serializable;import java.util.Set;import java.util.concurrent.TimeUnit;@Componentpublic class RedisManager implements CacheManager {    private final Logger logger = LoggerFactory.getLogger(RedisManager.class);    @Resource    private RedisTemplate redisTemplate;    @Override    public void init() {        RedisTemplate redisTemplate = SpringContextUtils.getBean("redisTemplate");        if (redisTemplate != null && this.redisTemplate == null) {            this.redisTemplate = redisTemplate;        }    }    @Override    public void remove(final String... keys) {        for (String key : keys) {            remove(key);        }    }    public void removePattern(final String pattern) {        Set
keys = redisTemplate.keys(pattern); if (!keys.isEmpty()) { redisTemplate.delete(keys); } } @Override public boolean remove(final String key) { if (exists(key)) { return redisTemplate.delete(key); } return true; } @Override public boolean exists(final String key) { return redisTemplate.hasKey(key); } @Override public Object get(final String key) { if (!exists(key)) { return null; } Object result = null; ValueOperations operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } @Override public boolean set(final String key, Object value) { Integer expire = defaultExpirationTime.intValue(); return set(key, value, expire); } @Override public boolean set(final String key, Object value, long expireTime) { boolean result = false; try { if (expireTime <= 0) { logger.warn("设置缓存时间不能小于0,key:{},value:{}", key, value); return result; } ValueOperations operations = redisTemplate.opsForValue(); operations.set(key, value); expire(key, expireTime); result = true; } catch (Exception e) { logger.warn("缓存设置失败,key:{},value:{}", key, value); } return result; } @Override public Boolean expire(final String key, final long timeout) { return redisTemplate.expire(key, timeout, TimeUnit.MINUTES); } @Override public Boolean expire(final String key, final long timeout, final TimeUnit unit) { return redisTemplate.expire(key, timeout, unit); } @Override public Long getExpire(final String key) { return redisTemplate.getExpire(key) == null ? 0 : redisTemplate.getExpire(key); } public void setRedisTemplate(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; } public RedisTemplate getRedisTemplate() { return redisTemplate; }}

RedisUtils

import org.springframework.context.annotation.DependsOn;import org.springframework.stereotype.Component;@Component@DependsOn(value = "springContextUtils")public class RedisUtils extends CacheContext
{ public RedisUtils() { super.init(); }}

SpringContextUtils

import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;@Componentpublic class SpringContextUtils implements ApplicationContextAware {    private static ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {        SpringContextUtils.applicationContext = applicationContext;    }    public static ApplicationContext getApplicationContext() {        assertApplicationContext();        return applicationContext;    }    @SuppressWarnings("unchecked")    public static 
T getBean(String beanName) { assertApplicationContext(); return (T) applicationContext.getBean(beanName); } public static
T getBean(Class
requiredType) { assertApplicationContext(); return applicationContext.getBean(requiredType); } private static void assertApplicationContext() { if (SpringContextUtils.applicationContext == null) { throw new RuntimeException("applicationContext属性为null,请检查是否注入了SpringContextHolder!"); } }}

Redis配置

# redis配置redis:    database: 0    host: 47.100.60.252    port: 8379    password: fdE#84K$EW~    timeout: 3000    jedis:        pool:            max-active: 8            max-idle: 8            max-wait: -1            min-idle: 0

使用说明

封装后的 Redis工具类使用起来异常简单,操作即可。

转载地址:http://pwjj.baihongyu.com/

你可能感兴趣的文章
python利用excel分析过杀漏失
查看>>
python判断汉字数目
查看>>
python判断文件是空的,如果是空的,就删除
查看>>
python判断密码是否正确_python密码判断是否符合要求的方法
查看>>
python判断字符串包含中文_Python 判断字符串是否包含中文
查看>>
python删除第一行_Python 乱码指北:一行删掉根目录
查看>>
Python删除列表元素的三种方法
查看>>
python初步学习-python数据类型-集合(set)
查看>>
python列表生成字典_Python中将字典转换为列表的方法
查看>>
python列表对应元素合并为列表及判断一个列表是几维
查看>>
python列表去重复后按照顺序_从包含不可共元素的Python列表中删除重复元素,同时保留顺序?...
查看>>
python列表前几个_python之列表
查看>>
python列表元组
查看>>
Python列表/元组/字典和集合使用
查看>>
python列表 行列选择_python_pandas_dataframe_行列选择_切片操作
查看>>
python列表
查看>>
python列出当前目录、子目录和文件的脚本
查看>>
python+flask计算机毕业设计骨科门诊患者档案管理系统(程序+开题+论文)
查看>>
python+flask计算机毕业设计高校体测管理系统的设计与实现(程序+开题+论文)
查看>>
Python切片对象和__getitem__
查看>>