不斷記錄中...
SpringBoot整合redis
pom依賴:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.11.2</version>
</dependency>
這裏用redisson,因爲項目中用了redisson做分佈式鎖。
配置(application-dev.yml):
spring:
application:
name: product-web
redis:
#數據庫索引
database: 0
host: 127.0.0.1
port: 6379
password: ******
jedis:
pool:
#最大連接數
max-active: 500
#最大空閒
max-idle: 1000
#最小空閒
min-idle: 4
max-wait: 6000ms
例 說明:
@Autowired
RedisTemplate redisTemplate;
@Autowired
StringRedisTemplate stringRedisTemplate;
redisTemplate.opsForValue().set(key, value);
redisTemplate.delete(key);
public void set(byte[] key, byte[] value) {
if (key != null) {
this.redisTemplate.opsForValue().set(key, value);
}
}
redis文件夾形式:
以:做key的分割線可設置歸類(文件夾形式)
@Test
public void distoryTest(){
String root = "root";
String path = "dir";
String key = "dirTestKey";
redisTemplate.opsForValue().set(root+":"+path+":"+key, "1");
}
顯示形式:
RedisClient,引用並封裝了上面兩個redisTemplate,可以直接執行get、set類似操作
import com.qulv.vdn.common.constant.ConfigConstant;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
@SuppressWarnings("ALL")
@Slf4j
@Component("redisClient")
public class RedisClient {
public static final long DEFAULT_EXPIRE = 86400L;
public static final long NOT_EXPIRE = -1L;
@Autowired
RedisTemplate redisTemplate;
@Autowired
StringRedisTemplate stringRedisTemplate;
@Resource(name = "stringRedisTemplate")
private ValueOperations<String, String> valueOperations;
@Resource(name = "stringRedisTemplate")
private HashOperations<String, String, String> hashOperations;
public void del(String key) {
if (this.exists(key)) {
this.stringRedisTemplate.delete(key);
}
}
public void set(String key, String value, long liveTime) {
if (!StringUtils.isBlank(key)) {
this.valueOperations.set(key, value);
if (liveTime != NOT_EXPIRE) {
this.stringRedisTemplate.expire(key, liveTime, TimeUnit.SECONDS);
}
}
}
public void set(String key, String value) {
this.set(key, value, NOT_EXPIRE);
}
public void set(byte[] key, byte[] value) {
if (key != null) {
this.redisTemplate.opsForValue().set(key, value);
}
}
public Set<String> scan(String pattern) throws Exception{
return ConfigConstant.OPEN_REDIS_CLUSTER_NO.equals("false") ? (Set)this.stringRedisTemplate.execute((RedisCallback<Set>) connection -> {
Cursor<byte[]> cursor = null;
Set<String> set = new HashSet<>();
try {
cursor = connection.scan(ScanOptions.scanOptions().count(2147483647L).match(pattern).build());
while(cursor.hasNext()) {
String element = new String((byte[])cursor.next());
set.add(element);
}
Set<String> var16 = set;
return set;
} catch (Exception var14) {
log.error("【[redisClient]使用scan出現異常,異常原因={}】", var14.getMessage());
} finally {
if (cursor != null) {
try {
cursor.close();
} catch (IOException var13) {
log.error("【[redisClient]關閉遊標異常,異常原因={}】", var13.getMessage());
}
}
}
return null;
}) : this.keysCluster(pattern);
}
public String get(String key) {
if (StringUtils.isBlank(key)) {
return null;
} else {
return this.stringRedisTemplate.opsForValue().get(key) == null ? null : this.stringRedisTemplate.opsForValue().get(key).toString();
}
}
public Set<String> keysCluster(String pattern) {
Set<String> result = new HashSet();
Set<String> nodesSet = this.getClusterNodes();
return (Set)(nodesSet == null && nodesSet.size() == 0 ? result : (Set)this.stringRedisTemplate.execute((RedisCallback<Set>)connection -> {
Iterator iterator = nodesSet.iterator();
while(iterator.hasNext()) {
byte[] args1 = pattern.getBytes();
byte[] args2 = ((String)iterator.next()).getBytes();
ArrayList object = (ArrayList)connection.execute("keys", new byte[][]{args1, args2});
Iterator it = object.iterator();
while(it.hasNext()) {
String keyName = new String((byte[])it.next());
result.add(keyName);
}
}
return result;
}));
}
public Set<String> getClusterNodes() {
return (Set)this.stringRedisTemplate.execute((RedisCallback<Set>)connection -> {
Set<String> nodes = new HashSet();
byte[] args1 = "nodes".getBytes();
byte[] object = (byte[])((byte[])connection.execute("cluster", new byte[][]{args1}));
if (object == null) {
return null;
} else {
String string = new String(object);
if (StringUtils.isEmpty(string)) {
return null;
} else {
String[] nodeInfoArray = string.split("\n");
for(int i = 0; i < nodeInfoArray.length; ++i) {
if (nodeInfoArray[i].contains("master")) {
String[] nodeInfo = nodeInfoArray[i].split(" ");
String nodeName = nodeInfo[0];
nodes.add(nodeName);
}
}
return nodes;
}
}
});
}
public void updateCmdStatus(String uin, String userName, String cmdId, String status) {
if (cmdId != null) {
this.set(uin + ":cmdId:" + userName + ":" + cmdId, status, DEFAULT_EXPIRE);
}
}
public String getCmdIdStatus(String uin, String userName, String cmdId) {
return this.get(uin + ":cmdId:" + userName + ":" + cmdId);
}
public void expire(String key, long liveTime) {
stringRedisTemplate.expire(key, liveTime, TimeUnit.SECONDS);
}
public Set<String> keys(String pattern) {
return this.stringRedisTemplate.keys(pattern);
}
public boolean exists(String key) {
return this.stringRedisTemplate.hasKey(key);
}
public void lpush(String key, String value) {
this.stringRedisTemplate.opsForList().leftPush(key, value);
}
public void rpush(String key, String value) {
this.stringRedisTemplate.opsForList().rightPush(key, value);
}
public Long llen(String key) {
return this.stringRedisTemplate.opsForList().size(key);
}
public String lindex(String key, Long index) {
return this.stringRedisTemplate.opsForList().index(key, index) == null ? null : this.stringRedisTemplate.opsForList().index(key, index).toString();
}
public String lpop(String key) {
try {
return this.stringRedisTemplate.opsForList().leftPop(key).toString();
} catch (NullPointerException n) {
//throw new NullPointerException(" opsForList is null ");
return null;
}
}
public List<String> lrange(String key, long start, long end) {
return this.stringRedisTemplate.opsForList().range(key, start, end);
}
public void hset(String key, String field, String value) {
this.hset(key, field, value, NOT_EXPIRE);
}
public void hset(String key, String field, String value, long liveTime) {
if (!StringUtils.isBlank(key)) {
hashOperations.put(key, field, value);
if (liveTime != NOT_EXPIRE) {
this.stringRedisTemplate.expire(key, liveTime, TimeUnit.SECONDS);
}
}
}
public void hsetAll(String key, Map<String, String> m, long liveTime) {
if (!StringUtils.isBlank(key)) {
hashOperations.putAll(key, m);
if (liveTime != NOT_EXPIRE) {
this.stringRedisTemplate.expire(key, liveTime, TimeUnit.SECONDS);
}
}
}
public void hsetAll(String key, Map<String, String> m) {
this.hsetAll(key, m, NOT_EXPIRE);
}
public String hget(String key, String field) {
return this.stringRedisTemplate.opsForHash().get(key, field) == null ? null : this.stringRedisTemplate.opsForHash().get(key, field).toString();
}
public void hdel(String key, String field) {
this.stringRedisTemplate.opsForHash().delete(key, new Object[]{field});
}
public Map<String, String> hgetall(String key) {
return this.hashOperations.entries(key);
}
public boolean hasKey(String key, String field) {
return this.stringRedisTemplate.opsForHash().hasKey(key, field);
}
public void hasInc(String key, String hashKey, long delta){
stringRedisTemplate.opsForHash().increment(key, hashKey, delta);
}
public Set zrang(String key, Long start, Long stop) {
return this.stringRedisTemplate.opsForZSet().range(key, start, stop);
}
public Set zrangeByScore(String key, double v1, double l1) {
return this.stringRedisTemplate.opsForZSet().rangeByScore(key, v1, l1);
}
public void zremrangeByScore(String key, double v1, double l1) {
this.stringRedisTemplate.opsForZSet().removeRangeByScore(key, v1, l1);
}
public void zadd(String key, String value, Long score) {
this.stringRedisTemplate.opsForZSet().add(key, value, (double)score);
}
public void zaddlive(String key, String value, Long score, long liveTime) {
this.stringRedisTemplate.opsForZSet().add(key, value, (double)score);
this.stringRedisTemplate.expire(key, liveTime, TimeUnit.SECONDS);
}
public void zremoveRange(String key, Long start, Long stop) {
this.stringRedisTemplate.opsForZSet().removeRange(key, start, stop);
}
public void saveMessage(String uin, String userName, String msgId, String message) {
this.hset(uin + ":message:" + userName, msgId, message);
}
public Set<String> getRedisMessageRecord(String uin, String wechatUserName, String wechatContactUserName) {
Set messageSet = null;
try {
messageSet = this.stringRedisTemplate.opsForZSet().reverseRange(uin + ":messageRecord:" + wechatUserName + ":" + wechatContactUserName, 0L, 30L);
} catch (Exception var6) {
var6.printStackTrace();
}
return messageSet;
}
}
使用示例:
/**
* 設置邀請碼
* @param user
*/
public String setInvitationCode(User user){
if (user.getUserId() == 1){
return "";
} else {
String code = UUIDUtil.getInvitationCode(user.getUserId()) ;
Set<String> keys = redisClient.keys("*#"+user.getUserId());
if (keys.isEmpty()){
//設置代理人相關信息
redisClient.set(code + "_vest_in", getAgentVestIn(user), 60 * 24 * 15);
redisClient.set(code, String.valueOf(user.getUserId()), 60 * 24 * 15);
user.setInviteCode(code);
}else {
code = keys.stream().findFirst().get();
}
return code;
}
}