1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.配置文件
下面提供两种配置文件类型properties和yml
#properties类型配置文件
#redis配置
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=127.0.0.1
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=1000
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=10000
#yml类型配置文件
#redis配置
spring:
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password:
# 连接超时时间(毫秒)
timeout: 1000
jedis.pool:
# 连接池最大连接数(使用负值表示没有限制)
max-active: 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: 1000
# 连接池中的最大空闲连接
max-idle: 8
# 连接池中的最小空闲连接
min-idle: 0
3.Redis配置类
package com.example.game.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* redis配置类
* @author sxd
* @date 2020/6/19 16:36
*/
@Configuration
public class RedisConfig {
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4.1.Redis工具类:java
package com.example.game.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
/**
* Redis工具类 RedisNXUtil
*/
@Component
public class RedisNxUtil {
public static final String LOCK_PREFIX = "REDIS_NX_LOCK";
/**
* ms
*/
public static final int LOCK_EXPIRE = 300;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RedisTemplate<String,String> stringRedisTemplate;
/**
* 分布式锁(防止死锁)
*
* @param key key
* @return 是否获取到
*/
public boolean lock(String key) {
String lock = LOCK_PREFIX + ":" + key;
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
long exprieAt = System.currentTimeMillis() + LOCK_EXPIRE + 1;
Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(exprieAt).getBytes());
if (acquire) {
return true;
} else {
byte[] value = connection.get(lock.getBytes());
if (Objects.nonNull(value) && value.length > 0) {
long expireTime = Long.parseLong(new String(value));
if (expireTime < System.currentTimeMillis()) {
// 如果锁已经过期
byte[] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1).getBytes());
// 防止死锁
return Long.parseLong(new String(oldValue)) < System.currentTimeMillis();
}
}
}
return false;
});
}
public void set(String key, String value, long timeout, TimeUnit timeUnit) {
stringRedisTemplate.opsForValue().set(key,value,timeout,timeUnit);
}
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
/**
* 删除锁
*
* @param key
*/
public void delete(String key) {
redisTemplate.delete(key);
}
/**
* 校验请求次数
*
* @param limitKey 校验的key
* @param limitTimes 限制的的请求次数
* @param timeout key失效的时常
* @param timeUnit key失效的时常的单位
* @return true 允许 false 不允许
*/
public boolean checkLimit(String limitKey, int limitTimes, long timeout, TimeUnit timeUnit) {
if (stringRedisTemplate.opsForValue().get(limitKey) != null) {
Long limitCount = incr(limitKey, timeout, timeUnit);
if (limitCount > limitTimes) {
return false;
}
}
return true;
}
/**
* key对应值自增
*
* @param key key
* @param liveTime key失效的时常
* @param timeUnit key失效的时常的单位
* @return 自增值
*/
public Long incr(String key, long liveTime, TimeUnit timeUnit) {
RedisAtomicLong entityIdCounter = new RedisAtomicLong(key, redisTemplate.getConnectionFactory());
Long increment = entityIdCounter.getAndIncrement();
//初始设置过期时间
if ((null == increment || increment.longValue() >= 0) && liveTime > 0) {
entityIdCounter.expire(liveTime, timeUnit);
}
return increment;
}
}
4.2.Redis工具类:Scala
@Service
class RedisTemplateService {
@Autowired var stringRedisTemplate: StringRedisTemplate = null
// 保存字符串, time是有效期(秒) time小于等于0为永久有效
def set(key: String, value: String, time: Int = -1) = {
stringRedisTemplate.opsForValue().set(key, value)
}
// 保存map, time是有效期(秒) time小于等于0为永久有效
def map(mapKey: String, key: String, value: String, time: Int = -1) = {
stringRedisTemplate.opsForHash[String, String]().put(mapKey, key, value)
stringRedisTemplate.expire(mapKey,time, TimeUnit.SECONDS);
}
// 删除
def del(key: String) = {
stringRedisTemplate.opsForHash().delete(key)
}
}
后面使用常规的方法调用就可以了