spring data redis快速上手

本文講述如何在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多實例配置》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章