This article is participating in the Java Theme Month – Java Debug Notes EventActive link
preface
Because Redis is needed to store some timeliness information in simple accounts, Redis is introduced
What is Redis?
Redis is an open source key-value structured database
Two, how to use?
The SpringBoot2.x project is used as an example here, and you can also see specific usage examples in the simple account example project
-
To install Redis, please refer to the official Redis website
-
Project increasing dependencies
<! -- redis --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency>Copy the code
- RedisUtil tools
/ * * *@author: create by bin
* @version: v1.0
* @description: Redis utility class *@dateAct: 2021/4/20 * * /
@Component
public class RedisUtil {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// =============================common============================
/** * specifies the cache expiration time **@paramThe key key *@paramTime Time (seconds) *@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; }}/** * Obtain expiration time by key **@paramThe key key cannot be NULL *@returnTime (s) returns 0 for permanently valid */
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/** * Check whether key exists **@paramThe key key *@returnTrue Exists false Does not exist */
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false; }}/** * delete cache **@paramKey can pass one 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=============================
/** * Ordinary cache fetch **@paramThe key key *@returnValue * /
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/** * Normal cache into **@paramThe key key *@paramThe value value *@returnTrue Successful false failed */
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false; }}/** * Normal cache is placed and set time **@paramThe key key *@paramThe value value *@paramTime Time (s) Time must be greater than 0. If time is less than or equal to 0, the value is set indefinitely *@returnTrue Successful false failed */
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; }}/** * increment **@paramThe key key *@paramDelta is incremented by a number (greater than 0) *@return* /
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("The increasing factor must be greater than zero.");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/** * decrements **@paramThe key key *@paramDelta is reduced by a number (less than 0) *@return* /
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("The decrement factor must be greater than zero.");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @paramThe key key cannot be NULL *@paramItem items cannot be null *@returnValue * /
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/** * get all keys ** corresponding to the hashKey@paramThe key key *@returnCorresponding multiple key values */
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @paramThe key key *@paramMap corresponds to multiple key values *@returnTrue Successful false failed */
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 **@paramThe key key *@paramMap corresponds to multiple key values *@paramTime Time (seconds) *@returnTrue Successful false failed */
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; }}/** * puts data into a hash table, or creates ** if none exists@paramThe key key *@paramItem item *@paramThe value value *@returnTrue Successful false failed */
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; }}/** * puts data into a hash table, or creates ** if none exists@paramThe key key *@paramItem item *@paramThe value value *@paramTime Time (s) Note: If the existing hash table has time, the original time * will be replaced@returnTrue Successful false failed */
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 the value ** from the hash table@paramThe key key cannot be NULL *@paramItem items can be more than null */
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/** * Determines whether the item value ** exists in the hash table@paramThe key key cannot be NULL *@paramItem items cannot be null *@returnTrue Exists false Does not exist */
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/** * hash increments that do not exist create one and return the new value **@paramThe key key *@paramItem item *@paramBy is going to be increased by how much (greater than 0) star@return* /
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/** * hash decrement **@paramThe key key *@paramItem item *@paramI'm going to subtract by (less than 0) star@return* /
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/** * Get all values in Set based on key **@paramThe key key *@return* /
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null; }}/** * select * from a set based on value@paramThe key key *@paramThe value value *@returnTrue Exists false Does not exist */
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false; }}/** * Put the data into the set cache **@paramThe key key *@paramValues can be multiple *@returnNumber of successes */
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0; }}/** * Put set data into cache **@paramThe key key *@paramTime Time (seconds) *@paramValues can be multiple *@returnNumber 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; }}/** * Get the length of the set cache **@paramThe key key *@return* /
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0; }}/** * removes ** of value@paramThe key key *@paramValues can be multiple *@returnNumber of removals */
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=================================
/** * retrieve the contents of the list cache **@paramThe key key *@paramStart to *@paramEnd End 0 to -1 represent 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; }}/** * Get the length of the list cache **@paramThe key key *@return* /
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0; }}/** * Get the value ** from the list by index@paramThe key key *@paramIndex index>=0, 0, 1, second element, and so on; When index<0, -1, the end of the table, the next-to-last element of -2, and so on@return* /
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null; }}/** * Put the list in the cache **@paramThe key key *@paramThe 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; }}/** * Put the list in the cache **@paramThe key key *@paramThe value value *@paramTime Time (seconds) *@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; }}/** * Put the list in the cache **@paramThe key key *@paramThe 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; }}/** * Put the list in the cache **@paramThe key key *@paramThe value value *@paramTime Time (seconds) *@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 a list of data ** based on the index@paramThe key key *@paramThe index index *@paramThe 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 values to value **@paramThe key key *@paramCount removes how many *@paramThe value value *@returnNumber of removals */
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; }}}Copy the code
- Using the example
Take storing a UUID of 60 seconds as an example
@Autowired
private RedisUtil redisUtil;
publicResult<? > generateUUID() {// Generate a 32-bit UUID (alphanumeric only)
String uuid = IDUtil.randomUUID();
// Put the UUID in Redis and set the 60s expiration time
redisUtil.set(uuid, new QrCodeInfoBO(), 60);
return Result.success(uuid);
}
Copy the code
Third, summary
If you share my passion for technology and root causes, please give my blog a thumbs up 8👍
Finally, I want to promote my open source project [simple account] (back end, front end, small program three open source), if you are interested, you can click Star~
Making address:
- Jane zhang backend
- Jane zhang front-end
- Simple account small procedures
Past the link
- Brief account main function introduction
- Brief introduction and deployment of back-end environment
- Brief introduction and deployment of front-end environment