Spring集成Redis
Pom.xml里:
<dependency><!--Redis-->
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application-local.yml里面
spring:
redis:
database: 0
host: 127.0.0.1 #需要配置
port: 6379 #需要配置
# password: # 密码(默认为空)
issingle: true
timeout: 100000 # 连接超时时长(毫秒)
jedis:
pool:
max-active: 500
max-idle: 500
max-wait: -1
min-idle: 0
max-redirects: 3
在 Spring的主启动main方法里:
public static void main(String[] args) {
SpringApplication sa = new SpringApplication(HbTaskApplication.class);
sa.addListeners(new MainBusiListeners());
sa.run(args);
}
MainBusiListeners.java如下:
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class MainBusiListeners implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
SpringContextHolder.initApplicationContext(event.getApplicationContext());
}
}
业务代码里 调用如下:
RedisSupport redisSupport = SpringContextHolder.getBean(RedisSupport.class);
Object token = redisSupport.get(TOKEN_REDIS_FLAG);
if (token != null) {
log.info(" TOKEN get From Redis:{}", token);
return String.valueOf(token);
}
....................
调用接口获取token
redisSupport.set(TOKEN_REDIS_FLAG, tokenStr, Long.getLong(authRes.getExpiresIn()));
MainBusiListeners.java如下:
package com.saas.digital.config;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
public class MainBusiListeners implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
SpringContextHolder.initApplicationContext(event.getApplicationContext());
}
}
RedisConfiguration.java如下:
package com.saas.digital.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
@Configuration
public class RedisConfiguration {
/**
* redis缓存组件
*
* @param redisTemplate
* @return
*/
@SuppressWarnings("rawtypes")
@Bean
@ConditionalOnMissingBean(RedisSupport.class)
public RedisSupport redisSupport(RedisTemplate redisTemplate) {
return new RedisSupport(redisTemplate);
}
}
RedisSupport 如下:
package com.saas.digital.config;
import org.springframework.data.redis.core.*;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* redis缓存管理支撑组件
*
* @author
* @file RedisSupport.java
* @since
* @date 2019年8月16日
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public class RedisSupport {
protected final RedisTemplate redisTemplate;
/**
* 构造方法
*
* @param redisTemplate
*/
public RedisSupport(RedisTemplate redisTemplate) {
super();
this.redisTemplate = redisTemplate;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置时效时间
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希获取数据
*
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表添加
*
* @param k
* @param v
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表获取
*
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l, long l1) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
/**
* 集合添加
*
* @param key
* @param value
*/
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* 集合获取
*
* @param key
* @return
*/
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
*
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key, Object value, double scoure) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
/**
* 有序集合获取
*
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
SpringContextHolder.java如下:
package com.saas.digital.config;
import org.apache.commons.lang3.Validate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候取出ApplicaitonContext.
*
* @author
* @date 2013-5-29 下午1:25:40
*/
public class SpringContextHolder implements ApplicationContextAware, DisposableBean {
private static ApplicationContext APPLICATION_CONTEXT = null;
private static Logger logger = LoggerFactory.getLogger(SpringContextHolder.class);
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
assertContextInjected();
return APPLICATION_CONTEXT;
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
assertContextInjected();
return (T) APPLICATION_CONTEXT.getBean(name);
}
/**
* 从静态变量applicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
public static <T> T getBean(Class<T> requiredType) {
assertContextInjected();
return APPLICATION_CONTEXT.getBean(requiredType);
}
/**
* 清除SpringContextHolder中的ApplicationContext为Null.
*/
public static void clearHolder() {
if (logger.isDebugEnabled()) {
logger.debug("清除SpringContextHolder中的ApplicationContext:" + APPLICATION_CONTEXT);
}
APPLICATION_CONTEXT = null;
}
/**
* 实现ApplicationContextAware接口, 注入Context到静态变量中.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
if (null == APPLICATION_CONTEXT) {
APPLICATION_CONTEXT = applicationContext;
}
}
/**
* 实现DisposableBean接口, 在Context关闭时清理静态变量.
*/
@Override
public void destroy() throws Exception {
SpringContextHolder.clearHolder();
}
/**
* 检查ApplicationContext不为空.
*/
private static void assertContextInjected() {
Validate.validState(APPLICATION_CONTEXT != null,
"applicaitonContext属性未注入, 请在applicationContext.xml中定义SpringContextHolder.");
}
/**
* 手动初始化
*
* @param applicationContext
* @since 0.0.1
*/
public static void initApplicationContext(ApplicationContext applicationContext) {
if (null == APPLICATION_CONTEXT) {
APPLICATION_CONTEXT = applicationContext;
}
}
}