当前位置:网站首页>Customize redistemplate tool class
Customize redistemplate tool class
2022-07-04 01:23:00 【gh_ xiaohe】
RedisTemplate
// Write our own RedisTemplate
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
// We develop for our own convenience , It is usually used directly <String, Object>
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
//Json Serialization configuration
//json Resolve any object
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
//ObjectMapper Transference
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//String Serialization
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key use String How to serialize
template.setKeySerializer(stringRedisSerializer);
// hash Of key Also used String How to serialize
template.setHashKeySerializer(stringRedisSerializer);
// value The serialization method adopts jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash Of value The serialization method adopts jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
RedisUtil
package com.gh.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Redis Tool class
* @author gh Email:@2495140780qq.com
* @Description
* @date 2022-02-14- Afternoon 2:06
*/
@Component
public final class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// =============================common============================
/**
* Specify cache expiration time
* @param key key
* @param time Time ( second )
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* according to key Get expiration time
* @param key key Not for null
* @return Time ( second ) return 0 Stands for permanent validity
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* Judge key Whether there is
* @param key key
* @return true There is false non-existent
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Delete cache
* @param key You can pass a value Or more
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* Normal cache fetch
* @param key key
* @return value
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* Normal cache put in
* @param key key
* @param value value
* @return true success false Failure
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* The normal cache is put in and set the time
* @param key key
* @param value value
* @param time Time ( second ) time Be greater than 0 If time Less than or equal to 0 Will be set indefinitely
* @return true success false Failure
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Increasing
* @param key key
* @param delta How much more should I add ( Greater than 0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException(" The increment factor must be greater than 0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* Decline
* @param key key
* @param delta To cut it down a few ( Less than 0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException(" The decline factor must be greater than 0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
* @param key key Not for null
* @param item term Not for null
* @return value
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* obtain hashKey All the corresponding key values
* @param key key
* @return Corresponding multiple key values
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
* @param key key
* @param map Corresponding to multiple key values
* @return true success false Failure
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet And set the time
* @param key key
* @param map Corresponding to multiple key values
* @param time Time ( second )
* @return true success false Failure
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* To a piece of hash Put data in the table , If it doesn't exist, it will create
* @param key key
* @param item term
* @param value value
* @return true success false Failure
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* To a piece of hash Put data in the table , If it doesn't exist, it will create
* @param key key
* @param item term
* @param value value
* @param time Time ( second ) Be careful : If there is already hash Watch has time , This will replace the original time
* @return true success false Failure
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Delete hash The values in the table
* @param key key Not for null
* @param item term Can make multiple Not for null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* Judge hash Whether there is a value of this item in the table
* @param key key Not for null
* @param item term Not for null
* @return true There is false non-existent
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash Increasing If it doesn't exist , It creates a And return the added value to
* @param key key
* @param item term
* @param by How much more should I add ( Greater than 0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash Decline
* @param key key
* @param item term
* @param by Remember less ( Less than 0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* according to key obtain Set All the values in
* @param key key
* @return
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* according to value From a set Query in , Whether there is
* @param key key
* @param value value
* @return true There is false non-existent
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Put data into set cache
* @param key key
* @param values value It can be more than one
* @return The number of successes
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* take set Data is put into the cache
* @param key key
* @param time Time ( second )
* @param values value It can be more than one
* @return The number of successes
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* obtain set The length of the cache
* @param key key
* @return
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* The removal value is value Of
* @param key key
* @param values value It can be more than one
* @return Number of removed
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* obtain list The contents of the cache
* @param key key
* @param start Start
* @param end end 0 To -1 For all values
* @return
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* obtain list The length of the cache
* @param key key
* @return
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Through the index obtain list The value in
* @param key key
* @param index Indexes index>=0 when , 0 Header ,1 The second element , By analogy ;index<0 when ,-1, Tail ,-2 The next to last element , By analogy
* @return
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* take list Put into cache
* @param key key
* @param value value
* @return
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* take list Put into cache
* @param key key
* @param value value
* @param time Time ( second )
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* take list Put into cache
* @param key key
* @param value value
* @return
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* take list Put into cache
*
* @param key key
* @param value value
* @param time Time ( second )
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* Modify according to the index list A piece of data in
* @param key key
* @param index Indexes
* @param value value
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* remove N The values are value
* @param key key
* @param count How many removed
* @param value value
* @return Number of removed
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
test
@Autowired
private RedisUtil redisUtil;
@Test
public void test() {
redisUtil.set("name", "kuangshen");
System.out.println(redisUtil.get("name"));
}
边栏推荐
- Oracle database knowledge points (IV)
- MySQL introduction - functions (various function statistics, exercises, details, tables)
- MySQL -- Introduction and use of single line functions
- Regular expression of shell script value
- It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
- Employees' turnover intention is under the control of the company. After the dispute, the monitoring system developer quietly removed the relevant services
- Beijing invites reporters and media
- MPLS experiment
- leetcode 121 Best Time to Buy and Sell Stock 买卖股票的最佳时机(简单)
- How to use AHAS to ensure the stability of Web services?
猜你喜欢
How to use AHAS to ensure the stability of Web services?
Function: find the sum of the elements on the main and sub diagonal of the matrix with 5 rows and 5 columns. Note that the elements where the two diagonals intersect are added only once. For example,
Long article review: entropy, free energy, symmetry and dynamics in the brain
Hash table, string hash (special KMP)
Infiltration learning diary day19
Function: write function fun to find s=1^k+2^k +3^k ++ The value of n^k, (the cumulative sum of the K power of 1 to the K power of n).
MySQL - use of aggregate functions and group by groups
Huawei BFD and NQA
功能:求5行5列矩阵的主、副对角线上元素之和。注意, 两条对角线相交的元素只加一次。例如:主函数中给出的矩阵的两条对角线的和为45。
打印菱形图案
随机推荐
Notice on Soliciting Opinions on the draft of information security technology mobile Internet application (APP) life cycle security management guide
“疫”起坚守 保障数据中台服务“不打烊”
2-redis architecture design to use scenarios - four deployment and operation modes (Part 2)
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
swagger中响应参数为Boolean或是integer如何设置响应描述信息
Long article review: entropy, free energy, symmetry and dynamics in the brain
Cloud dial test helps Weidong cloud education to comprehensively improve the global user experience
It's OK to have hands-on 8 - project construction details 3-jenkins' parametric construction
C import Xls data method summary V (complete code)
@EnableAsync @Async
OS interrupt mechanism and interrupt handler
Sequence list and linked list
Function: find the sum of the elements on the main and sub diagonal of the matrix with 5 rows and 5 columns. Note that the elements where the two diagonals intersect are added only once. For example,
be based on. NETCORE development blog project starblog - (14) realize theme switching function
Wechat official account and synchronization assistant
查询效率提升10倍!3种优化方案,帮你解决MySQL深分页问题
The FISCO bcos console calls the contract and reports an error does not exist
Some other configurations on Huawei's spanning tree
Fundamentals of machine learning: feature selection with lasso
Mongodb learning notes: command line tools