引入redis依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.1.5.RELEASE</version>
</dependency>
application.properties配置
#RedisProperties
spring.redis.database=1
spring.redis.host=<ip>
spring.redis.port=6379
spring.redis.password=<密码>
直接上工具类源码
package com.nowcoder.community.util;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.io.Closeable;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.concurrent.TimeUnit;
@Component
public class RedisUtils {
public static final FastDateFormat DATE_HHmmss = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
private static final String lockPrefix = "LOCK:";
@Autowired
private StringRedisTemplate redisTemplate;
public StringRedisTemplate redisTemplate() {
return this.redisTemplate;
}
/**
* 缓存是否存在
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key
* @return
*/
public String get(final String key) {
ValueOperations<String, String> operations = redisTemplate.opsForValue();
return operations.get(key);
}
public List<String> mget(final String... keys) {
ValueOperations<String, String> operations = redisTemplate.opsForValue();