一文搞定 Spring Data Redis 詳解及實戰

轉載自  一文搞定 Spring Data Redis 詳解及實戰

SDR - Spring Data Redis的簡稱。

Spring Data Redis提供了從Spring應用程序輕鬆配置和訪問Redis的功能。它提供了與商店互動的低級別和高級別抽象,使用戶免受基礎設施問題的困擾。

Spring Boot 實戰

引用依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>${spring-boot.version}</version>
</dependency>

添加redis配置類

@EnableCaching
@Configuration
public class RedisConfig extends CachingConfigurerSupport {

    @Bean
    public KeyGenerator keyGenerator() {
        return (Object target, Method method, Object... params) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(method.getName());
            for (Object obj : params) {
                sb.append(obj.toString());
            }
            return sb.toString();
        };
    }

    @Bean
    public CacheManager cacheManager(RedisTemplate redisTemplate) {
        RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
        cacheManager.setDefaultExpiration(10000);
        return cacheManager;
    }

    @Bean
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        template.setValueSerializer(getSerializer(template));
        template.afterPropertiesSet();
        return template;
    }

    private RedisSerializer getSerializer(StringRedisTemplate template) {
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        serializer.setObjectMapper(om);

        return serializer;
    }

}

添加redis配置參數:

spring.redis:
  database: 0 # Redis數據庫索引(默認爲0)
  host: 192.168.1.168
  port: 6379
  #password: 123456
  timeout: 0 # 連接超時時間(毫秒)
  pool: 
    max-active: 8 # 連接池最大連接數(使用負值表示沒有限制)
    max-idle: 8 # 連接池中的最大空閒連接
    max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制)
    min-idle: 0 # 連接池中的最小空閒連接

開始使用

@Autowired
private RedisTemplate redisTemplate;

...
redisTemplate.opsForValue().set("test", System.currentTimeMillis());
...

通過 RedisTemplate 處理對象

大多數用戶可能會使用RedisTemplate它的相應軟件包org.springframework.data.redis.core-由於其豐富的功能集,模板實際上是Redis模塊的中心類。該模板提供了Redis交互的高級抽象。雖然RedisConnection提供接受和返回二進制值(byte數組)的低級別方法,但模板負責序列化和連接管理,使用戶無需處理這些細節。

此外,該模板提供了操作視圖,它提供豐富的,通用的接口,用於針對特定類型或某些鍵(通過KeyBound接口)進行操作,如下所述:

鍵類型操作:

接口 描述
GeoOperations Redis的地理空間操作,如GEOADD,GEORADIUS..
HashOperations Redis散列類型操作
HyperLogLogOperations Redis的HyperLogLog操作,如PFADD,PFCOUNT..
ListOperations Redis列表操作
SetOperations Redis集合操作
ValueOperations Redis字符串操作
ZSetOperations Redis有序集合操作

鍵綁定操作:

接口 描述
BoundGeoOperations Redis的地理空間操作
BoundHashOperations Redis散列類型鍵綁定操作
BoundKeyOperations Redis鍵綁定操作
BoundListOperations Redis列表鍵綁定操作
BoundSetOperations Redis集合鍵綁定操作
BoundValueOperations Redis字符串鍵綁定操作
BoundZSetOperations Redis有序集合鍵綁定操作

怎麼使用?

Spring Boot實戰Redis章節配置完成後,使用Spring直接注入即可。

public class Example {

  @Autowired
  private RedisTemplate<String, String> template;

  @Resource(name="redisTemplate")
  private ListOperations<String, String> listOps;

  public void addLink(String userId, URL url) {
    listOps.leftPush(userId, url.toExternalForm());
  }
}

RedisTemplate是線程安全的,開箱即用,可以在多個實例中重複使用。

RedisTemplate和StringRedisTemplate區別?

org.springframework.data.redis.core.RedisTemplate

org.springframework.data.redis.core.StringRedisTemplate

1、StringRedisTemplate繼承自RedisTemplate

2、StringRedisTemplate默認使用String序列化方式,RedisTemplate默認使用jdk自帶的序列化方式。

3、兩者數據不互通,只能各自管理各自處理過的數據。

推薦使用StringRedisTemplate。

直接與Redis對話

直接底層的與Redis對話,沒有封裝。默認配置只能一個數據庫,如下,可以直接通過獲取StringRedisConnection來切換當前操作的數據庫。

stringRedisTemplate.execute((RedisCallback<Boolean>) connection -> {
    StringRedisConnection stringRedisConnection = (StringRedisConnection) connection;
    stringRedisConnection.select(5);
    stringRedisConnection.set("name", "zoe");
    return true;
});

序列化器

從Spring Data Redis框架本身的角度看,存放到redis的數據只是字節,雖然Redis本身支持各種類型,但大部分是指數據存儲的方式,而不是它所代表的內容,由用戶決定是否將字節轉換爲字符串或其他對象。

用戶自定義類型和原始數據之間的轉換由org.springframework.data.redis.serializer包中的序列化器進行處理。

這個包下面主要包含了兩種類型的序列化器:

  • 基於RedisSerializer的雙向串行器。

  • 元素的讀寫使用的RedisElementReader和RedisElementWriter。

它們的主要區別是,RedisSerializer序列化成byte[],而後者使用的是ByteBuffer。

序列化器實現類

這裏有幾種開箱即用的實現,其中有兩種在之前的文章已經涉及過。

實現 描述
StringRedisSerializer String/byte[]轉換,速度快
JdkSerializationRedisSerializer JDK自帶序列化
OxmSerializer XML序列化,佔空間,速度慢
Jackson2JsonRedisSerializer JSON序列化,需要定義JavaType
GenericJackson2JsonRedisSerializer JSON序列化,無需定義JavaType

所以,如果只是簡單的字符串類型,使用StringRedisSerializer就可以了,如果要有對象就使用Json的序列化吧,可以很方便的組裝成對象。

事務支持

Spring Data Redis提供了對Redis的事務支持,如:multi, exec, discard命令。

Spring Data Redis提供了SessionCallback接口,在同一個連接中需要執行多個操作時使用,與使用Redis事務時一樣。

示例

@Test
public void testTransaction() {
    List<Object> txResults = (List<Object>) stringRedisTemplate
            .execute(new SessionCallback<List<Object>>() {
                public List<Object> execute(RedisOperations operations)
                        throws DataAccessException {
                    operations.multi();
                    operations.opsForSet().add("t1", "value1");
                    operations.opsForSet().add("t2", "value2");
                    operations.opsForSet().add("t3", "value3");
                    return operations.exec();
                }
            });
    txResults.forEach(e -> logger.info("txResults: " + e));
}

以上代碼,是一個接受字符串值的模板,RedisTemplate會使用相應的序列化器,如果把value3換成非字符串333,那第3條會報錯,前面兩個也不會保存成功。

當然,exec方法也可以接受自定義的序列化器

List<Object> exec(RedisSerializer<?> valueSerializer);

@Transactional註解支持

註解事務支持在默認情況下是禁用的,必須通過把RedisTemplate設置明確開啓事務支持:setEnableTransactionSupport(true),如果沒有錯誤即成功,有錯誤就全部回滾。當前連接所有寫操作都會進入操作隊列,讀操作會轉移到一個新的連接。

示例配置

@Configuration
public class RedisTxContextConfiguration {
  @Bean
  public StringRedisTemplate redisTemplate() {
    StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
    // explicitly enable transaction support
    template.setEnableTransactionSupport(true);
    return template;
  }

  @Bean
  public PlatformTransactionManager transactionManager() throws SQLException {
    return new DataSourceTransactionManager(dataSource());
  }

  @Bean
  public RedisConnectionFactory redisConnectionFactory( // jedis || lettuce);

  @Bean
  public DataSource dataSource() throws SQLException { // ... }
}

使用約束

// 綁定到當前線程上的連接
template.opsForValue().set("foo", "bar");

// 讀操作不參與事務
connection template.keys("*");

// 當在事務中設置的值不可見時返回null
template.opsForValue().get("foo");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章