3つの方法のSpringBoot統合Redisの

  • 自動構成のロード
  • 独自のコードの負荷を書きます
  • XMLのロード

これらの三つの方法が必要とされている使用します。

1. [追加の依存

2.書き込み設定情報

= 0 spring.redis.database
spring.redis.host = localhostを
spring.redis.port = 6379
#接続タイムアウト時間(ミリ秒)
spring.redis.timeout = 3000

#最大接続プールアイドル状態の接続は、デフォルト値は8です。
8-IDLE = spring.redis.pool.max
#最小接続プールアイドル接続、デフォルト値は0です。
IDLE = 0-spring.redis.pool.minの
#割り当ての場合-1、それは限定されない示し、一方はプールが割り当てられている場合MAXACTIVE jedis例えば、この時点で、プール状態(排気)に排出されます。
アクティブ=。8-spring.redis.pool.max
使用可能な接続を待機する#の最大時間は、ミリ秒単位で、デフォルト値は-1、タイムアウトしません。待機時間を超えた場合は、直接投げJedisConnectionException
spring.redis.pool.maxは待機を= - 1

方法1:使用自動設定が自動的に読み込ま。

上記スプリングブート開始データは、Redisの導入のため、負荷の構成プロパティRedisAutoConfigurationクラスファイルに使用することができます。


**
 *標準Redisの構成。
 * /
@Configuration
保護静的クラスRedisConfiguration {

    @Bean
    @ConditionalOnMissingBean(名= "redisTemplate")
    公衆RedisTemplate <オブジェクト、オブジェクト> redisTemplate(
            RedisConnectionFactory redisConnectionFactory)は
                    UnknownHostExceptionが{スロー
        RedisTemplate <オブジェクト、オブジェクト>テンプレート=新しいRedisTemplate <オブジェクト、オブジェクト>();
        template.setConnectionFactory(redisConnectionFactory)。
        テンプレートを返します。
    }

    @Bean
    @ConditionalOnMissingBean(StringRedisTemplate.class)
    StringRedisTemplate stringRedisTemplate(パブリック
            RedisConnectionFactory redisConnectionFactory)
                    スローUnknownHostExceptionが{
        StringRedisTemplateテンプレート=新しいStringRedisTemplate()。
        template.setConnectionFactory(redisConnectionFactory)。
        テンプレートを返します。
    }
}

、applicaitonにロードされたコンフィギュレーションをデフォルトになります。この方法でのRedis 2つのBeanを提供

RedisTemplateは<オブジェクト、オブジェクト>すべてのRedisの、キー値のデータ型オブジェクト上で動作することができる、オブジェクトはデフォルトの直列JdkSerializationRedisSerializerを使用します。

StringRedisTemplate Redisのは運営とString型のキー値データすることができます。

第二の方法:独自のコードを記述がロードされます。

@Configuration
パブリッククラスRedisConfig {

  プライベートロガーロガー= LoggerFactory.getLogger(this.getClass());

  @value( "$ {spring.redis.host}")
  プライベート文字列ホスト。

  @value( "$ {spring.redis.port}")
  プライベートint型ポート。

  @value( "$ {spring.redis.timeout}")
  プライベートint型のタイムアウト。

  @value( "$ {spring.redis.password}")
  プライベート文字列のパスワード。

  @value( "$ {spring.redis.database}")
  プライベートint型のデータベース;

  @value( "$ {spring.redis.pool.maxアイドル}")
  プライベートint型maxIdle。

  @value( "$ {spring.redis.pool.minアイドル}")
  プライベートint型minIdle。

  / **
  * Redisの模板、存储关键字是字符串、值是JDK序列化
  * @description:
  * @param工場
  * @return
  * /
  @Bean
  公共RedisTemplateの<string、オブジェクト> redisTemplate(RedisConnectionFactory工場){
      RedisTemplate <文字列、OBJECT> redisTemplate =新しいredisTemplate <>();
      redisTemplate.setConnectionFactory(工場)。
      RedisSerializer <文字列> redisSerializer =新しいStringRedisSerializer();
      redisTemplate.setKeySerializer(redisSerializer)。
      redisTemplate.setHashKeySerializer(redisSerializer)。
      // JdkSerializationRedisSerializer序列化方式。
      JdkSerializationRedisSerializer jdkRedisSerializer =新しいJdkSerializationRedisSerializer();
      redisTemplate.setValueSerializer(jdkRedisSerializer)。
      redisTemplate.setHashValueSerializer(jdkRedisSerializer)。
      redisTemplate.afterPropertiesSet();
      redisTemplateを返します。
  }
}

三つの方法:使用してXMLをロード。

プログラムのエントリに追加されます。

@ImportResource(位置= { "クラスパス:スプリングredis.xml"})

新しい春-redis.xml下のリソースファイルフォルダで

<豆のxmlns =」http://www.springframework.org/schema/beans "
    のxmlns:XSI =" http://www.w3.org/2001/XMLSchema-instance "のxmlns:キャッシュ=" のhttp:// WWW .springframework.org /スキーマ/キャッシュ "
    のxmlns:コンテキスト=" http://www.springframework.org/schema/context "
    のxsi:schemaLocationの=" http://www.springframework.org/schema/beans
    のhttp:// www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache.xsd
        HTTP ://www.springframework.org/schema/context  
    http://www.springframework.org/schema/context/spring-context-4.0.xsd「>

    <ビーンID = "jedisPoolConfig"クラス= "redis.clients.jedis.JedisPoolConfig">
        <プロパティ名= "minIdle"値= "$ {redis.pool.minIdle}" />
        <プロパティ名= "maxIdle"値=」 $ {redis.pool.maxIdle}」/>
        <プロパティ名= "maxWaitMillis"値= "$ {redis.pool.maxWaitMillis}" />
    </豆>

    <ビーンID = "jedisConnectionFactory"
        クラス= "org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
        <プロパティ名= "usePool"値= "TRUE"> </ property>の
        <プロパティ名= "ホスト名"の値= "$ {redis.ip}" />
        <プロパティ名= "ポート"値= "$ {redis.port}" />
        <プロパティ名= "パスワード"値= "$ {redis.password}" />
        <プロパティ名= "タイムアウト"値= "$ {redis.timeout}" />
        <プロパティ名= "データベース"値= "$ {redis.default.db}"> </ property>の
        <コンストラクタ引数-REF = "jedisPoolConfig "/>
    </豆>

    <ビーンID = "redisTemplate"クラス= "org.springframework.data.redis.core.RedisTemplate">
        <プロパティ名= "はconnectionFactory" REF = "jedisConnectionFactory" />
        <プロパティ名= "KeySerializer">
            <ビーン
                クラス=」 org.springframework.data.redis.serializer.StringRedisSerializer "> </豆>
        </ property>の
        <プロパティ名=" ValueSerializer ">
            <豆の
                クラス=" org.springframework.data.redis.serializer.JdkSerializationRedisSerializer "> </豆>
        </ property>の
        <プロパティ名= "HashKeySerializer">
            <豆の
                クラス= "org.springframework.data.redis.serializer.StringRedisSerializer"> </豆>
        </プロパティ>
        <プロパティ名= "HashValueSerializer">
            <豆の
                クラス= "org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"> </豆>
        </ property>の
    </豆>
</豆>

使用します。

テンプレートは直接だけで罰金を呼び出す注釈を注入しました。

@Repository
パブリッククラスRedisService {

    @Autowired
    StringRedisTemplate stringRedisTemplate。

    公共のボイドの追加(文字列のキー、ユーザーのユーザー、長い時間){
        Gson gson =新しいGson();
        stringRedisTemplate.opsForValue()セット(キー、gson.toJson(ユーザ)、時間、TimeUnit.MINUTES)。
    }

    公共のボイドの追加(文字列のキー、一覧<ユーザー>ユーザー、長い時間){
        Gson gson =新しいGson();
        列src = gson.toJson(ユーザー);
        stringRedisTemplate.opsForValue()セット(キー、SRC、時間、TimeUnit.MINUTES)。
    }

    公開ユーザGET(文字列キー){
        文字列のソース= stringRedisTemplate.opsForValue()(キー)を得ます。
        (もし!StringUtils.isEmpty(ソース)){
            (新しいGsonを返す)fromJson(ソース、User.class)。
        }
        はnullを返します。
    }

    公共の一覧<ユーザ> getUserList(文字列のキー){
        String型のソース= stringRedisTemplate.opsForValue()(キー)を取得します。
        (もし!StringUtils.isEmpty(ソース)){
            。返す新しいGson()fromJson(ソース、新しいTypeToken <リスト<ユーザ>>(){
            } .getType());
        }
        はnullを返します。
    }

    公共ボイド削除(文字列キー){
        。。stringRedisTemplate.opsForValue()getOperations()(キー)を削除します。
    }
}

テストが続いている場合:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
パブリッククラスRedisTest {

    @Autowired
    RedisService redisService。

    @Before
    公共ボイドセットアップ(){

    }

    @Test
    ます。public voidのget(){
        ユーザのユーザ=新しいユーザー();
        user.setName( "wangjianfeng");
        user.setAge(22)。
        redisService.add( "userByName:" + user.getName()、ユーザー、10L)。
        リスト<ユーザ>リスト=新しいArrayListを<>();
        list.add(ユーザ)。
        redisService.add( "リスト"、リスト、10L)。
        ユーザーUSER1 = redisService.get( "userByName:wangjianfeng");
        Assert.notNull(USER1、 "ユーザーがnull");
        リスト<ユーザ>リスト2 = redisService.getUserList( "リスト");
        Assert.notNull(LIST2、 "リストがnull");
    }
}

Redisのキャッシュを使用SpringBoot:

:Springbootのような、多くのキャッシュマネージャを提供しています

  • SimpleCacheManager
  • EhCacheManager
  • CaffeineCacheManager
  • GuavaCacheManager
  • CompositeCacheManager

SpringDataは、キャッシュマネージャを提供します。RedisCacheManager

SpringBoot、プログラム内のエントリで、一緒に自動注釈マネージャを@EnableCaching適切な構成を有します。

そして、私たちは自分のコードの設定を記述するために使用し、RedisConfig @EnableCachingは注釈を追加、変更、および継承CachingCongigurerSupport

@Configuration
@EnableCaching
パブリッククラスRedisConfigはCachingConfigurerSupportを拡張します{
    ...
}

おすすめ

転載: www.linuxidc.com/Linux/2020-03/162648.htm