Spring Data操作Redisデータベースの詳細

3917 ワード

RedisはNOSQLデータベースで、KeyValue形式でデータを格納します.データはメモリ形式で存在するか、ファイルシステムに永続化することができます.Spring dataはRedisをよくパッケージ化しており、使い勝手も十分です.Redisはオープンソース(BSDライセンス)であり、メモリ内のデータ構造ストレージシステムであり、データベース、キャッシュ、メッセージミドルウェアとして使用することができる.文字列(strings)、ハッシュ(hashes)、リスト(lists)、セット(sets)、順序付きセット(sorted sets)、範囲クエリー、bitmaps、hyperlogs、地理空間(geospatial)インデックス半径クエリーなど、さまざまなタイプのデータ構造をサポートします.Redisにはレプリケーション(replication)、LUAスクリプト(Lua scripting)、LRU駆動イベント(LRU eviction)、トランザクション(transactions)、および異なるレベルのディスク持続化(persistence)、Redis哨兵(Sentine)および自動パーティション(Cluster)による高可用性(highavailability)が内蔵されています.
1.システム構成、Mavenで開発する場合、pom.xmlファイルに次の構成を追加します.


  
    org.springframework.data
    spring-data-redis
    1.8.1.RELEASE
  

そのため、Spring Dataテンプレートはbeanが直接使用する場所で直接注入しやすいように構成することができます.



2.Redis Templateは異なる需要に対して以下の操作を分類してカプセル化した.

opsForValue() - Operations for working with entries having simple values
opsForList() - Operations for working with entries having list values
opsForSet() - Operations for working with entries having set values
opsForZSet() - Operations for working with entries having ZSet (sorted set) values
opsForHash() - Operations for working with entries having hash values
boundValueOps(K) - Operations for working with simple values bound to a given key
boundListOps(K) - Operations for working with list values bound to a given key
boundSetOps(K) - Operations for working with set values bound to a given key
boundZSet(K) - Operations for working with ZSet (sorted set) values bound to a given key
boundHashOps(K) - Operations for working with hash values bound to a given key

3.一般的な操作例
3.1 Redis Template注入、直接テンプレート注入、またはops形式で注入、以下の例では両方について説明した.

public class Example {
  // inject the actual template
  @Autowired
  private RedisTemplate template;
  // inject the template as ListOperations
  // can also inject as Value, Set, ZSet, and HashOperations
  @Resource(name="redisTemplate")
  private ListOperations listOps;
  public void addLink(String userId, URL url) {
    listOps.leftPush(userId, url.toExternalForm());
    // or use template directly
    template.boundListOps(userId).leftPush(url.toExternalForm());
  }
}

3.2 Boundシリーズの操作例では、Boundシリーズの操作の利点は、一度バインドするだけで、一連の操作を行うことができ、コードが非常に精錬されていることです.

 BoundListOperations mangoOps = redis.boundListOps("solidmango");
  Product popped = mangoOps.rightPop();
  mangoOps.rightPush(product1);
  mangoOps.rightPush(product2);
  mangoOps.rightPush(product3);

3.3 Serializer構成例では、通常、KeyとValueは異なる方法で永続化されます.次の例では、KeyはStringで永続化され、ValueはJackson形式で永続化されます.

@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory rcf) {
    RedisTemplate redis =
    new RedisTemplate();
    redis.setConnectionFactory(rcf);
    redis.setKeySerializer(new StringRedisSerializer());
    redis.setValueSerializer(
    new Jackson2JsonRedisSerializer(Product.class));
    return redis;
}

まとめ
Spring Data操作Redisの構成と開発方式について詳しく分析し、構成部分では具体的な構成方式、コード例部分では3つの状況に分けて具体的な解決策を示し、皆さんの役に立つことを願っています.