SpringDataRedis(SpringData)

はじめに:レタス、データベースおよびオペレーティングRedisのと、データベース接続の内側に書かれたレタスで

回路図:

1.依存関係

<! - https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis - > 
<依存> 
    <groupIdを> org.springframework.data </ groupIdを> 
    <たartifactId>春-DATA- Redisの</たartifactId> 
    <バージョン> 2.1.9.RELEASE </バージョン> 
</依存関係>

データベース接続Redisの2.SpringData

•SRC /メイン/プロファイルは/ dev /設定/ redis.properties設定ファイルを作成し、devがソースフォルダです。このプロファイルのすべての設定とRedisの関連のプロパティ。

redis.host = Redisのサーバーデータベース接続のRedisの// IPアドレスまたはホスト名
redis.port = 6379 //ポート
redis.auth = hellolee //認証情報
redis.database = 0 //データベースのインデックス番号
redis.pool .maxTotal =コネクタ接続プールの総数は10 //最大
redis.pool.maxIdle = 5 //接続プールは、接続の最大数を維持
接続の最小数によって維持redis.pool.minIdle = 3 //接続プール
redis.poolを。 testOnBorrow後= // trueが、すべての接続テストを返します

•SRC /メイン/リソース/春/春-base.xmlプロファイルにあるパッケージスキャンredis.propertiesを追加します。

<コンテキスト:コンポーネント・スキャンベースパッケージ=「com.yootk.redis.config」/>

•設定書込みクラスSpringDataRedisConfig.java

パッケージcom.yootk.redis.config。
輸入org.apache.commons.pool2.impl.GenericObjectPoolConfig; 
輸入org.springframework.beans.factory.annotation.Autowired; 
輸入org.springframework.beans.factory.annotation.Value。
輸入org.springframework.context.annotation.Bean。
輸入org.springframework.context.annotation.Configuration。
輸入org.springframework.context.annotation.PropertySource。
輸入org.springframework.data.redis.connection.RedisConnectionFactory; 
輸入org.springframework.data.redis.connection.RedisPassword; 
輸入org.springframework.data.redis.connection.RedisStandaloneConfiguration。
輸入org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration。
輸入org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
輸入org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration。

@Configuration 
@PropertySource( "クラスパス:設定/ redis.properties")
パブリッククラスSpringDataRedisConfig { 
    @Bean( "redisConfiguration")
    公衆RedisStandaloneConfiguration getRedisConfiguration(
            @value( "$ {redis.host}")文字列ホスト名、
            @value( "$ {redis.port} ")int型ポート、
            @value(" $ {redis.auth} ")文字列のパスワード、
            @value(" $ {} redis.database」 
        configuration.setHostName(で、hostName)。//设置Redisの主机名称
        configuration.setPort(ポート); //设置のRedis的访问端口
        configuration.setPassword(RedisPassword.of(パスワード)); //设置密码
        configuration.setDatabase(データベース)。//设置数据库索引
        リターン構成。
    } 
    @Bean( "objectPoolConfig")
    公衆GenericObjectPoolConfig getObjectPoolConfig(
            @value( "$ {redis.pool.maxTotal}")maxTotal、int型
            @value( "$ {redis.pool.maxIdleは}")maxIdle、int型
            @valueを(」 $ {redis.pool.minIdle} ")INT minIdle、
            @value(" $ {redis.pool.testOnBorrow}」)ブールtestOnBorrow 
    ){ 
        =新しいGenericObjectPoolConfig GenericObjectPoolConfig poolConfig()。
        poolConfig.setMaxTotal(maxTotal)。
        poolConfig。 
        poolConfig.setMinIdle(minIdle); 
        poolConfig.setTestOnBorrow(testOnBorrow); 
        poolConfig返す; 
    } 
    @Bean( "lettuceClientConfiguration")を
    公衆LettuceClientConfiguration getLettuceClientConfiguration(
            @Autowired GenericObjectPoolConfig poolConfig 
    ){//接続プールアセンブリレタスを作成しますクライアント構成オブジェクト
        リターンLettucePoolingClientConfiguration.builder()poolConfig(poolConfig).build();. 
    } @Bean(「redisConnectionFactory」)//この実施形態では、インスタンス化の一例に相当し、前述の二重引用符をredisConnectionFactoryクラスオブジェクトコンテンツは、オブジェクトである   。この方法の実装はコンストラクタの実装に相当するので、この方法は、自動的に実行される場合、//自動的に他の場所でこのオブジェクト回注射します。
    公共RedisConnectionFactory getConnectionFactory(
    
@Autowired RedisStandaloneConfiguration redisConfiguration、 @Autowired LettuceClientConfiguration lettuceClientConfiguration ){ LettuceConnectionFactoryはconnectionFactory =新しいLettuceConnectionFactory(redisConfiguration、lettuceClientConfiguration)。 connectionFactoryを返します。 } }

 Redisのは、現在の通常の接続かどうかをテストするテストクラスを書くことができます

パッケージcom.yootk.test。
輸入org.junit.Test; 
輸入org.junit.runner.RunWith; 
輸入org.springframework.beans.factory.annotation.Autowired; 
輸入org.springframework.data.redis.connection.RedisConnectionFactory; 
輸入org.springframework.test.context.ContextConfiguration。
輸入org.springframework.test.context.junit4.SpringJUnit4ClassRunner。

@ContextConfiguration(位置= { "クラスパス:春/ * XML"})
@RunWith(SpringJUnit4ClassRunner.class)
パブリッククラスTestRedisConnection { 
    @Autowired 
    プライベートRedisConnectionFactory redisConnectionFactory。
    @Test  
    公共ボイドtestRedis(){
        のSystem.out.println(this.redisConnectionFactory)。//输出连接工厂实例
        this.redisConnectionFactory.getConnection()flushDb();. // データベースをクリア
    } 
}

3.RedisTemplate

•2つのメソッドを追加し、コンフィギュレーション・クラスSpringDataRedisConfig.javaを変更

    @Bean( "stringRedisTemplate")
    公衆RedisTemplate getStringRedisTempalate(
            @Autowired RedisConnectionFactoryはconnectionFactory 
    ){ 
        StringRedisTemplate redisTemplate =新しいStringRedisTemplate()。
        redisTemplate.setConnectionFactory(はconnectionFactory)。
        redisTemplateを返します。
    } 
    @Bean( "redisTemplate")
    公衆RedisTemplate getRedisTempalate(
            @Autowired RedisConnectionFactoryはconnectionFactory 
    ){ 
        RedisTemplate <文字列、文字列> redisTemplate =新しいRedisTemplate <>(); 
        redisTemplate.setConnectionFactory(はconnectionFactory)。
        redisTemplateを返します。
    }

•テストStringRedisTemplate

パッケージcom.yootk.test。
輸入org.junit.Test; 
輸入org.junit.runner.RunWith; 
輸入org.springframework.beans.factory.annotation.Autowired; 
輸入org.springframework.data.redis.core.RedisTemplate。
輸入org.springframework.test.context.ContextConfiguration。
輸入org.springframework.test.context.junit4.SpringJUnit4ClassRunner。
輸入java.util.HashMapを; 
輸入java.util.Map; 
輸入java.util.Set; 

@ContextConfiguration(位置= { "クラスパス:春/ * XML"})
@RunWith(SpringJUnit4ClassRunner.class)
パブリッククラスTestRedisTemplateBase { 
    @Autowired 
    プライベートRedisTemplate <文字列、文字列> stringRedisTemplate。
    @テスト
    公共ボイドたTestString(){
        {(x ++; X <10整数X = 0)のための
            ( - + X、 "ハロー" - "MSG" + X)this.stringRedisTemplate.opsForValue()セット。
        } 
    } 
    @Test 
    公共ボイドtestHash(){ 
        地図<文字列、文字列>マップ=新しいHashMapの<>(); 
        map.put( "名前"、 "可爱的小李老师"); 
        map.put( "年齢"、String.valueOf(16)); 
        map.put( "給与"、String.valueOf(1.1)); 
        this.stringRedisTemplate.opsForHash()のputAll( "メンバーリー"、マップ)。
        System.out.println(this.stringRedisTemplate.opsForHash())( "メンバー・リー"、 "名前"を取得します。); 
        設定して<文字列>キー=のthis.stringRedisTemplate.keys( "MSG - *"); 
        System.out.println( "【所有的キー】" +キー)。
    } 
}

•テストRedisTemplate

パッケージcom.yootk.test。
輸入org.junit.Test; 
輸入org.junit.runner.RunWith; 
輸入org.springframework.beans.factory.annotation.Autowired; 
輸入org.springframework.dao.DataAccessException。
輸入org.springframework.data.redis.connection.RedisConnection。
輸入org.springframework.data.redis.core.RedisCallback; 
輸入org.springframework.data.redis.core.RedisTemplate。
輸入org.springframework.test.context.ContextConfiguration。
輸入org.springframework.test.context.junit4.SpringJUnit4ClassRunner。

@ContextConfiguration(位置= { "クラスパス:春/ * XML"})
@RunWith(SpringJUnit4ClassRunner.class)
パブリッククラスTestRedisTemplate { 
    @Autowired
    プライベートRedisTemplate <文字列、文字列> redisTemplate。

    @Test 
    ます。public voidたTestStringは(){ 
        this.redisTemplate.execute(新しいRedisCallback <オブジェクト>(){// Redisの回调
            @Override 
            パブリックオブジェクトdoInRedis(RedisConnection接続)DataAccessException {スロー
                connection.flushDbを(); //清空数据库
                リターン」 OK "; 
            } 
        }); 
        {(; X <10×++整数X = 0)のため
            。this.redisTemplate.opsForValue()セット( "message-" + X "こんにちは- " + X)。
        } 
    } 
    @Test 
    公共ボイドtestGet(){
        System.err.println( "【获取数据】" + this.redisTemplate.opsForValue()( "メッセージ-3")を取得します。)。
    } 
}

前記格納されたオブジェクトの配列:オブジェクトクラスデータベースRedisのに格納されているが、ストレス:オブジェクト・クラスに対応する直列化実装しなければなりません。

  そしてStringRedisTemplate差RedisTemplate:StringRedisTemplate RedisTemplateは、プロセスシーケンスの一連の文字列を提供します。

  JSONシリアル化メカニズムに基づいて、JDKシリアライズ処理機構:SpringDataRedisに二つの方法で標的配列の内部動作を処理します。Javaコードは、ああすることによって達成され、完全にデータの使用の汎用性を考慮すると、JDK機構のパフォーマンスが使用されている考慮に入れる場合はJSONメカニズムです。

オブジェクトを格納するため•利用JDKメカニズム、コンフィギュレーション・クラスSpringDataRedisConfig.javaを変更

@Bean( "redisTemplate")//元のメソッドgetRedisTempalate今変更
    公共RedisTemplate getRedisTempalate(
            @Autowired RedisConnectionFactoryザはconnectionFactoryを
    ){ 
        RedisTemplate <文字列オブジェクト> =新しい新しいRedisTemplate redisTemplate <>(); 
        redisTemplate.setConnectionFactory(はconnectionFactory)。
        redisTemplate.setKeySerializer(新しいStringRedisSerializer());キー//文字列のストレージのデータ
        redisTemplate.setValueSerializer(新JdkSerializationRedisSerializer()); //は、オブジェクトの値が保存
        redisTemplate.setHashKeySerializer(新しいStringRedisSerializerを()); // データキー文字列がで保存されている
        redisTemplate.setHashValueSerializer(新しいJdkSerializationRedisSerializer()); // オブジェクトの値が保存
        リターンredisTemplateを。
    }

•オブジェクトを格納するためにJSONメカニズムを使用して、コンフィギュレーション・クラスSpringDataRedisConfig.javaを変更 

    @Bean( "redisTemplate")//元のメソッドgetRedisTempalate今変更
    公共RedisTemplate getRedisTempalate(
            @Autowired RedisConnectionFactoryザはconnectionFactoryを
    ){ 
        RedisTemplate <文字列オブジェクト> =新しい新しいRedisTemplate redisTemplate <>(); 
        redisTemplate.setConnectionFactory(はconnectionFactory)。
        redisTemplate.setKeySerializer(新しいStringRedisSerializer());キー// によって格納された文字列データ
        redisTemplate.setValueSerializer(新しいJackson2JsonRedisSerializer(Object.classを)) ; //は、 オブジェクトの値を保存
        redisTemplate.setHashKeySerializer(新StringRedisSerializer()); / で保存されたキー/データ列
        redisTemplate.setHashValueSerializer(新しいJackson2JsonRedisSerializer(Object.classを)) ; // オブジェクトの値を保存
        redisTemplateを返します。
    }

5.Pipelineライン(詳細はノートを参照してください)

おすすめ

転載: www.cnblogs.com/wxl123/p/11110392.html