ホームページ  >  記事  >  データベース  >  Redis で複数のデータベースを構成する方法

Redis で複数のデータベースを構成する方法

WBOY
WBOY転載
2023-05-28 15:49:061565ブラウズ

はじめに

redis にはデフォルトでデータベース 0 ~ 16 があります。通常、redis を操作するときはデータベース 0 を使用しますが、プロジェクトによっては複数のデータベースを同時に操作したい場合があります。毎回他のデータベースにアクセスしたい データベースのデータを選択する際に、データベースを切り替えるのが面倒

そのため、複数の Jedis Client を設定する必要がありますが、Jedis はブロックされやすく効率があまり良くないため、ここでは Reactive 接続方式で比較的効率の良い Lettuce Client を使用します。しかし、Lettuce Client を使用するにはどうすればよいでしょうか? 実際には、通常、spring-boot-starter-data-redis 依存関係を追加し、RedisTemplate を通じて Redis 機能を使用します。バージョンが非常に高い場合、デフォルトの RedisTemplate の最下層は Lettuce Client を使用して接続と操作を確立します。データ。

1. pom 依存関係を追加します

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.0.5.RELEASE</version>
</dependency>

2. 複数のデータ ソースの構成とスプリング コンテナーへの追加

下のスクリーンショットでは 4 つのデータ ソース、つまりライブラリ No. を使用しています。 1、2、3、4。

1) 新しい構成構成クラスを作成します

2) new RedisStandaloneConfiguration(host, port); Redis 構成を初期化し、ライブラリ番号を選択します。

3) LettuceConnectionFactory を初期化します。

4) RedisTemplate をインスタンス化し、キー値のシリアル化メソッドを設定します。ここではキーと値は両方とも文字列であるため、シリアライザーは StringRedisSerializer を選択します。

5) 3番目で作成したLettuceConnectionFactoryをRedisTemplateに設定し、@Beanアノテーションを付けてSpringコンテナに注入します 使用する場合は直接Springコンテナ内でメソッド名で検索してアセンブルしますそれを参照するインスタンスにコピーします。

import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.ObjectUtils;
 
import java.time.Duration;
 
/**
* reactive redis
* @Author:wangqipeng
* @Date:14:38 2019-07-03
*/
 
@Configuration
public class RedisDatasourceConfiguration {
 
    @Value("${redis.isCleanRedisCache:false}")
    private String cleanRedisCache;
    @Value("${redis.host:127.0.0.1}")
    public String host;
    @Value("${redis.port:6379}")
    public Integer port;
    private String password;
 
    @Value("${redis.timeout:2000}")
    public Integer timeout;
    public Integer maxIdle = 16;
    public Integer minIdle = 5;
    public Integer maxTotal = 30;
 
 
    @Bean
    public RedisTemplate<String, String> stringRedisTemplate1() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
        configuration.setDatabase(1);
        if (!ObjectUtils.isEmpty(password)) {
            RedisPassword redisPassword = RedisPassword.of(password);
            configuration.setPassword(redisPassword);
        }
        return createRedisTemplate(creatFactory(configuration));
    }
 
    @Bean
    public RedisTemplate<String, String> stringRedisTemplate2() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
        configuration.setDatabase(2);
        if (!ObjectUtils.isEmpty(password)) {
            RedisPassword redisPassword = RedisPassword.of(password);
            configuration.setPassword(redisPassword);
        }
        return createRedisTemplate(creatFactory(configuration));
    }
    @Bean
    public RedisTemplate<String, String> stringRedisTemplate3() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
        configuration.setDatabase(3);
        if (!ObjectUtils.isEmpty(password)) {
            RedisPassword redisPassword = RedisPassword.of(password);
            configuration.setPassword(redisPassword);
        }
        return createRedisTemplate(creatFactory(configuration));
    }
    @Bean
    public RedisTemplate<String, String> stringRedisTemplate4() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
        configuration.setDatabase(4);
        if (!ObjectUtils.isEmpty(password)) {
            RedisPassword redisPassword = RedisPassword.of(password);
            configuration.setPassword(redisPassword);
        }
        return createRedisTemplate(creatFactory(configuration));
    }
 
    @Bean
    public RedisTemplate<String, String> stringRedisTemplate5() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
        configuration.setDatabase(5);
        if (!ObjectUtils.isEmpty(password)) {
            RedisPassword redisPassword = RedisPassword.of(password);
            configuration.setPassword(redisPassword);
        }
        return createRedisTemplate(creatFactory(configuration));
    }
 
    private RedisTemplate<String, String> getSerializerRedisTemplate(){
        RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        return redisTemplate;
    }
 
    private RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, String> redisTemplate = getSerializerRedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    private GenericObjectPoolConfig getGenericObjectPoolConfig(){
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxTotal(maxTotal);
        genericObjectPoolConfig.setMinIdle(minIdle);
        genericObjectPoolConfig.setMaxIdle(maxIdle);
        genericObjectPoolConfig.setMaxWaitMillis(timeout);
        return genericObjectPoolConfig;
    }
 
    private LettuceConnectionFactory creatFactory(RedisStandaloneConfiguration configuration){
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
        builder.poolConfig(getGenericObjectPoolConfig());
 
//        LettuceClientConfiguration.LettuceClientConfigurationBuilder builder = LettuceClientConfiguration.builder();
//        builder.clientResources(clientResources());
//        builder.commandTimeout(Duration.ofSeconds(3000));
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(configuration, builder.build());
        connectionFactory.afterPropertiesSet();
        return connectionFactory;
    }
}

3. 使い方

Redis で複数のデータベースを構成する方法

ここで参照するのは、上記の @Bean を通じて Spring コンテナにロードされるライブラリ No.2 です。

以上がRedis で複数のデータベースを構成する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事はyisu.comで複製されています。侵害がある場合は、admin@php.cn までご連絡ください。