本文讲述如何在spring boot中集成redis,并使用redis进行操作。下一篇我们讲redis实战
maven配置如下:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
properties文件配置:
# Redis数据库索引(默认为0)
spring.redis.database=0
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
配置文件如下:
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate<String,Integer> stringIntegerRedisTemplate(RedisConnectionFactory redisConnectionFactory){
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
Jackson2JsonRedisSerializer<Integer> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Integer>(Integer.class);
RedisTemplate<String,Integer> redisTemplate = new RedisTemplate<>();
//设置连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
//针对所有数据类型key序列化对象
redisTemplate.setKeySerializer(stringRedisSerializer);
//针对所有数据类型value序列化对象
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
//针对hash类型数据key的序列化对象
redisTemplate.setHashKeySerializer(stringRedisSerializer);
//针对hash类型数据value的序列化对象
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
常用的操作接口
操作接口 | 作用 |
---|---|
GeoOperations | Redis的地理空间操作的,比如GEOADD,GEORADIUS… |
HashOperations | Redis哈希操作 |
HyperLogLogOperations | Redis的HyperLogLog操作,例如PFADD,PFCOUNT,… |
ListOperations | Redis列表操作 |
SetOperations | Redis设置操作 |
ValueOperations | Redis字符串(或值)操作 |
ZSetOperations | Redis zset(或排序集)操作 |
案例
public class SequenceGenerator {
private static final String KEY_PREFIX = "PROJECT_NAME_SEQUENCE:";
private static final DateTimeFormatter DTF=DateTimeFormatter.ofPattern("yyyyMMdd");
@Setter
private RedisTemplate<String,Integer> redisTemplate;
/**
* 获取递增序列号
*
* @param
* @return
*/
public Long next() {
String key = KEY_PREFIX + DTF.format(LocalDate.now());
return redisTemplate.opsForValue().increment(key, 1);
}
}
绑定操作
绑定对应的key对应的数据结构进行操作。
绑定操作 | 作用 |
---|---|
BoundGeoOperations | Redis键绑定地理空间操作 |
BoundHashOperations | Redis哈希键绑定操作 |
BoundKeyOperations | Redis按键绑定操作 |
BoundListOperations | Redis列表键绑定操作 |
BoundSetOperations | Redis设置键绑定操作 |
BoundValueOperations | Redis字符串(或值)键绑定操作 |
BoundZSetOperations | Redis zset(或排序集)键绑定操作 |
Spring Boot Redis多实例配置请参考这篇文章:
《Spring Boot Redis多实例配置》