博客
关于我
封装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/

你可能感兴趣的文章
Nginx upstream性能优化
查看>>
Nginx 中解决跨域问题
查看>>
Nginx 动静分离与负载均衡的实现
查看>>
Nginx 反向代理 MinIO 及 ruoyi-vue-pro 配置 MinIO 详解
查看>>
Nginx 反向代理解决跨域问题
查看>>
Nginx 反向代理配置去除前缀
查看>>
nginx 后端获取真实ip
查看>>
Nginx 学习总结(17)—— 8 个免费开源 Nginx 管理系统,轻松管理 Nginx 站点配置
查看>>
nginx 常用配置记录
查看>>
Nginx 我们必须知道的那些事
查看>>
Nginx 的 proxy_pass 使用简介
查看>>
Nginx 的配置文件中的 keepalive 介绍
查看>>
Nginx 负载均衡与权重配置解析
查看>>
Nginx 负载均衡详解
查看>>
nginx 配置 单页面应用的解决方案
查看>>
nginx 配置https(一)—— 自签名证书
查看>>
nginx 配置~~~本身就是一个静态资源的服务器
查看>>
Nginx 配置解析:从基础到高级应用指南
查看>>
Nginx下配置codeigniter框架方法
查看>>
nginx添加模块与https支持
查看>>