这编文章主要介绍了springboot整合redis,以及redis配置和一些redis操作数据的工具类。
首先倒入redis依赖
一.依赖
org.springframework.boot
spring-boot-starter-data-redis
二.配置文件
创建一个redis.properties配置redis
redis.host=localhost
redis.port=6379
redis.password=
redis.database=1
redis.maxActive=8
redis.maxWait=-1
redis.maxIdle=8
redis.minIdle=1
redis.timeOut=0
创建一个与redis.properties的配置类方便直接使用配置的参数。
@Configuration
@PropertySource(value = "classpath:redis.properties")
@ConfigurationProperties(prefix = "redis")
public class RedisConfigProperties {
// 主机地址
public String host;
//端口
public int port;
//密码没有不填写
public String password;
// Redis数据库索引(默认为0)
public int database;
//最大活跃连接
public int maxActive;
//连接池最大阻塞等待时间(使用负值表示没有限制)
public int maxWait;
//连接池中的最大空闲连接
public int maxIdle;
//连接池中的最小空闲连接
public int minIdle;
//连接超时时间(毫秒)
public int timeOut;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public int getMaxIdle() {
return maxIdle;
}
public void setMaxIdle(int maxIdle) {
this.maxIdle = maxIdle;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
public int getTimeOut() {
return timeOut;
}
public void setTimeOut(int timeOut) {
this.timeOut = timeOut;
}
}
三.整合配置
听说某宝的fastjson的json和序列化性能很好这里的序列化我们使用fastjson的序列化。
创建一个自定义序列化配置类
public class FastJson2JsonRedisSerializer implements RedisSerializer {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
private Class clazz;
public FastJson2JsonRedisSerializer(Class clazz) {
super();
this.clazz = clazz;
}
public byte[] serialize(T t) throws SerializationException {
if (t == null) {
return new byte[0];
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
return (T) JSON.parseObject(str, clazz);
}
}
将项目进行整合
@Configuration
public class RedisConfig {
@Autowired
private RedisConfigProperties redis;
@Bean
public RedisSerializer fastJson2JsonRedisSerializer() { ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
return new FastJson2JsonRedisSerializer
四.操作数据工具类
接口:
public interface BaseRedisDao {
/**
* 用户排序通过注册时间的 权重值
* @param date
* @return
*/
double getCreateTimeScore(long date);
/**
* 获取Redis中所有的键的key
* @return
*/
Set getAllKeys();
/**
* 获取所有的普通key-value
* @return
*/
Map getAllString();
/**
* 获取所有的Set -key-value
* @return
*/
Map> getAllSet();
/**
* 获取所有的ZSet正序 -key-value 不获取权重值
* @return
*/
Map> getAllZSetReverseRange();
/**
* 获取所有的ZSet倒序 -key-value 不获取权重值
* @return
*/
Map> getAllZSetRange();
/**
* 获取所有的List -key-value
* @return
*/
Map> getAllList();
/**
* 获取所有的Map -key-value
* @return
*/
Map> getAllMap();
/**
* 添加一个list
* @param key
* @param objectList
*/
void addList(K key, List objectList);
/**
* 向list中增加值
* @param key
* @param obj
* @return 返回在list中的下标
*/
long addList(K key,V obj);
/**
* 向list中增加值
* @param key
* @param obj
* @return 返回在list中的下标
*/
long addList(K key,V ...obj);
/**
*
* 输出list
* @param key List的key
* @param s 开始下标
* @param e 结束的下标
* @return
*/
List getList(K key, long s, long e);
/**
* 输出完整的list
* @param key
*/
List getList(K key);
/**
* 获取list集合中元素的个数
* @param key
* @return
*/
long getListSize(K key);
/**
* 移除list中某值
* 移除list中 count个value为object的值,并且返回移除的数量,
* 如果count为0,或者大于list中为value为object数量的总和,
* 那么移除所有value为object的值,并且返回移除数量
* @param key
* @param object
* @return 返回移除数量
*/
long removeListValue(K key,V object);
/**
* 移除list中某值
* @param key
* @param object
* @return 返回移除数量
*/
long removeListValue(K key,V... object);
/**
* 批量删除key对应的value
* @param keys
*/
void remove(final K... keys);
/**
* 删除缓存
* 根据key精确匹配删除
* @param key
*/
void remove(final K key);
/**
* 通过分数删除ZSet中的值
* @param key
* @param s
* @param e
*/
void removeZSetRangeByScore(String key,double s , double e);
/**
* 设置Set的过期时间
* @param key
* @param time
* @return
*/
Boolean setSetExpireTime(String key,Long time);
/**
* 设置ZSet的过期时间
* @param key
* @param time
* @return
*/
Boolean setZSetExpireTime(String key,Long time);
/**
* 判断缓存中是否有key对应的value
* @param key
* @return
*/
boolean exists(final K key);
/**
* 读取String缓存 可以是对象
* @param key
* @return
*/
V get(final K key);
/**
* 读取String缓存 可以是对象
* @param key
* @return
*/
List get(final K... key);
/**
* 读取缓存 可以是对象 根据正则表达式匹配
* @param regKey
* @return
*/
List
实现类
@Repository("redisHandle")
public class RedisHandle implements BaseRedisDao {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource(name="redisTemplate")
protected RedisTemplate redisTemplate;
/**
* 出异常,重复操作的次数
*/
private static Integer times = 5;
public double getCreateTimeScore(long date) {
return date/ 100000.0;
}
public Set getAllKeys() {
return redisTemplate.keys("*");
}
public Map getAllString() {
Set stringSet = getAllKeys();
Map map = new HashMap();
Iterator iterator = stringSet.iterator();
while (iterator.hasNext()) {
String k = iterator.next();
if (getType(k) == DataType.STRING) {
map.put(k, get(k));
}
}
return map;
}
public Map> getAllSet() {
Set stringSet = getAllKeys();
Map> map = new HashMap>();
Iterator iterator = stringSet.iterator();
while (iterator.hasNext()) {
String k = iterator.next();
if (getType(k) == DataType.SET) {
map.put(k, getSet(k));
}
}
return map;
}
public Map> getAllZSetRange() {
Set stringSet = getAllKeys();
Map> map = new HashMap>();
Iterator iterator = stringSet.iterator();
while (iterator.hasNext()) {
String k = iterator.next();
if (getType(k) == DataType.ZSET) {
logger.debug("k:"+k);
map.put(k, getZSetRange(k));
}
}
return map;
}
public Map> getAllZSetReverseRange() {
Set stringSet = getAllKeys();
Map> map = new HashMap>();
Iterator iterator = stringSet.iterator();
while (iterator.hasNext()) {
String k = iterator.next();
if (getType(k) == DataType.ZSET) {
map.put(k, getZSetReverseRange(k));
}
}
return map;
}
public Map> getAllList() {
Set stringSet = getAllKeys();
Map> map = new HashMap>();
Iterator iterator = stringSet.iterator();
while (iterator.hasNext()) {
String k = iterator.next();
if (getType(k) == DataType.LIST) {
map.put(k, getList(k));
}
}
return map;
}
public Map> getAllMap() {
Set stringSet = getAllKeys();
Map> map = new HashMap>();
Iterator iterator = stringSet.iterator();
while (iterator.hasNext()) {
String k = iterator.next();
if (getType(k) == DataType.HASH) {
map.put(k, getMap(k));
}
}
return map;
}
public void addList(String key, List objectList) {
for (Object obj : objectList) {
addList(key, obj);
}
}
public long addList(String key, Object obj) {
return redisTemplate.boundListOps(key).rightPush(obj);
}
public long addList(String key, Object... obj) {
return redisTemplate.boundListOps(key).rightPushAll(obj);
}
public List getList(String key, long s, long e) {
return redisTemplate.boundListOps(key).range(s, e);
}
public List getList(String key) {
return redisTemplate.boundListOps(key).range(0, getListSize(key));
}
public long getListSize(String key) {
return redisTemplate.boundListOps(key).size();
}
public long removeListValue(String key, Object object) {
return redisTemplate.boundListOps(key).remove(0, object);
}
public long removeListValue(String key, Object... objects) {
long r = 0;
for (Object object : objects) {
r += removeListValue(key, object);
}
return r;
}
public void remove(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
remove(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
public void removeBlear(String... blears) {
for (String blear : blears) {
removeBlear(blear);
}
}
public Boolean renameIfAbsent(String oldKey, String newKey) {
return redisTemplate.renameIfAbsent(oldKey, newKey);
}
public void removeBlear(String blear) {
redisTemplate.delete(redisTemplate.keys(blear));
}
public void removeByRegular(String... blears) {
for (String blear : blears) {
removeBlear(blear);
}
}
public void removeByRegular(String blear) {
Set stringSet = getAllKeys();
for (String s : stringSet) {
if (Pattern.compile(blear).matcher(s).matches()) {
redisTemplate.delete(s);
}
}
}
public void removeMapFieldByRegular(String key, String... blears) {
for (String blear : blears) {
removeMapFieldByRegular(key, blear);
}
}
public void removeMapFieldByRegular(String key, String blear) {
Map map = getMap(key);
Set stringSet = map.keySet();
for (String s : stringSet) {
if (Pattern.compile(blear).matcher(s).matches()) {
redisTemplate.boundHashOps(key).delete(s);
}
}
}
public Long removeZSetValue(String key, Object... value) {
return redisTemplate.boundZSetOps(key).remove(value);
}
public void removeZSet(String key) {
removeZSetRange(key, 0L, getZSetSize(key));
}
public void removeZSetRange(String key, Long start, Long end) {
redisTemplate.boundZSetOps(key).removeRange(start, end);
}
public void setZSetUnionAndStore(String key,String key1, String key2) {
redisTemplate.boundZSetOps(key).unionAndStore(key1,key2);
}
public Set getZSetRange(String key) {
return getZSetRange(key, 0, getZSetSize(key));
}
public Set getZSetRange(String key, long s, long e) {
return redisTemplate.boundZSetOps(key).range(s, e);
}
public Set getZSetReverseRange(String key) {
return getZSetReverseRange(key, 0, getZSetSize(key));
}
public Set getZSetReverseRange(String key, long start, long end) {
return redisTemplate.boundZSetOps(key).reverseRange(start, end);
}
public Set getZSetRangeByScore(String key, double start, double end) {
return redisTemplate.boundZSetOps(key).rangeByScore(start, end);
}
public Set getZSetReverseRangeByScore(String key, double start, double end) {
return redisTemplate.boundZSetOps(key).reverseRangeByScore(start, end);
}
public Set> getZSetRangeWithScores(String key, long start, long end) {
return redisTemplate.boundZSetOps(key).rangeWithScores(start, end);
}
public Set> getZSetReverseRangeWithScores(String key, long start, long end) {
return redisTemplate.boundZSetOps(key).reverseRangeWithScores(start, end);
}
public Set> getZSetRangeWithScores(String key) {
return getZSetRangeWithScores(key, 0, getZSetSize(key));
}
public Set> getZSetReverseRangeWithScores(String key) {
return getZSetReverseRangeWithScores(key, 0, getZSetSize(key));
}
public long getZSetCountSize(String key, double sMin, double sMax) {
return redisTemplate.boundZSetOps(key).count(sMin, sMax);
}
public long getZSetSize(String key) {
return redisTemplate.boundZSetOps(key).size();
}
public double getZSetScore(String key, Object value) {
return redisTemplate.boundZSetOps(key).score(value);
}
public double incrementZSetScore(String key, Object value, double delta) {
return redisTemplate.boundZSetOps(key).incrementScore(value, delta);
}
public Boolean addZSet(String key, double score, Object value) {
return redisTemplate.boundZSetOps(key).add(value, score);
}
public Long addZSet(String key, TreeSet value) {
return redisTemplate.boundZSetOps(key).add(value);
}
public Boolean addZSet(String key, double[] score, Object[] value) {
if (score.length != value.length) {
return false;
}
for (int i = 0; i < score.length; i++) {
if (addZSet(key, score[i], value[i]) == false) {
return false;
}
}
return true;
}
public void remove(String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
public void removeZSetRangeByScore(String key,double s , double e) {
redisTemplate.boundZSetOps(key).removeRangeByScore(s,e);
}
public Boolean setSetExpireTime(String key, Long time) {
return redisTemplate.boundSetOps(key).expire(time, TimeUnit.SECONDS);
}
public Boolean setZSetExpireTime(String key, Long time) {
return redisTemplate.boundZSetOps(key).expire(time, TimeUnit.SECONDS);
}
public boolean exists(String key) {
return redisTemplate.hasKey(key);
}
public Object get(int key) {
return this.get(String.valueOf(key));
}
public Object get(long key) {
return this.get(String.valueOf(key));
}
public Object get(String key) {
return redisTemplate.boundValueOps(key).get();
}
public List get(String... keys) {
List list = new ArrayList();
for (String key : keys) {
list.add(get(key));
}
return list;
}
public List getByRegular(String regKey) {
Set stringSet = getAllKeys();
List objectList = new ArrayList();
for (String s : stringSet) {
if (Pattern.compile(regKey).matcher(s).matches() && getType(s) == DataType.STRING) {
objectList.add(get(s));
}
}
return objectList;
}
public void set(long key, Object value) {
this.set(String.valueOf(key) ,value);
}
public void set(int key, Object value) {
this.set(String.valueOf(key) ,value);
}
public void set(String key, Object value) {
redisTemplate.boundValueOps(key).set(value);
}
public void set(String key, Object value, Long expireTime) {
redisTemplate.boundValueOps(key).set(value, expireTime, TimeUnit.SECONDS);
}
public boolean setExpireTime(String key, Long expireTime) {
return redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
}
public DataType getType(String key) {
return redisTemplate.type(key);
}
public void removeMapField(String key, Object... field) {
redisTemplate.boundHashOps(key).delete(field);
}
public Long getMapSize(String key) {
return redisTemplate.boundHashOps(key).size();
}
public Map getMap(String key) {
return redisTemplate.boundHashOps(key).entries();
}
public T getMapField(String key, String field) {
return (T) redisTemplate.boundHashOps(key).get(field);
}
public Boolean hasMapKey(String key, String field) {
return redisTemplate.boundHashOps(key).hasKey(field);
}
public List getMapFieldValue(String key) {
return redisTemplate.boundHashOps(key).values();
}
public Set getMapFieldKey(String key) {
return redisTemplate.boundHashOps(key).keys();
}
public void addMap(String key, Map map) {
redisTemplate.boundHashOps(key).putAll(map);
}
public void addMap(String key, String field, Object value) {
redisTemplate.boundHashOps(key).put(field, value);
}
public void addMap(String key, String field, Object value, long time) {
redisTemplate.boundHashOps(key).put(field, value);
redisTemplate.boundHashOps(key).expire(time, TimeUnit.SECONDS);
}
public void watch(String key) {
redisTemplate.watch(key);
}
public void addSet(String key, Object... obj) {
redisTemplate.boundSetOps(key).add(obj);
}
public long removeSetValue(String key, Object obj) {
return redisTemplate.boundSetOps(key).remove(obj);
}
public long removeSetValue(String key, Object... obj) {
if (obj != null && obj.length > 0) {
return redisTemplate.boundSetOps(key).remove(obj);
}
return 0L;
}
public long getSetSize(String key) {
return redisTemplate.boundSetOps(key).size();
}
public Boolean hasSetValue(String key, Object obj) {
Boolean boo = null;
int t =0;
while (true){
try {
boo = redisTemplate.boundSetOps(key).isMember(obj);
break;
} catch (Exception e) {
logger.error("key[" + key + "],obj[" + obj + "]判断Set中的值是否存在失败,异常信息:" + e.getMessage());
t++;
}
if(t>times){
break;
}
}
logger.info("key[" + key + "],obj[" + obj + "]是否存在,boo:" + boo);
return boo;
}
public Set getSet(String key) {
return redisTemplate.boundSetOps(key).members();
}
public Set getSetUnion(String key, String otherKey) {
return redisTemplate.boundSetOps(key).union(otherKey);
}
public Set getSetUnion(String key, Set set) {
return redisTemplate.boundSetOps(key).union(set);
}
public Set getSetIntersect(String key, String otherKey) {
return redisTemplate.boundSetOps(key).intersect(otherKey);
}
public Set getSetIntersect(String key, Set set) {
return redisTemplate.boundSetOps(key).intersect(set);
}
}
五.单元测试
创建一个测试的base了后面的类只需要继承这个父类即可
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=App.class)
@WebAppConfiguration
public class BaseTest {
}
测试:
public class RedisTest extends BaseTest {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@Resource
RedisHandle rs;
@Test
public void RedisTest() throws Exception {
rs.set(1, "11");
System.out.println(rs.get(1));
}
}
文章来源: http://www.haha174.top/article/details/251216
项目源码: https://github.com/haha174/boot.git