>  기사  >  Java  >  springboot가 여러 redis 연결을 구성하는 방법에 대한 심층 분석

springboot가 여러 redis 연결을 구성하는 방법에 대한 심층 분석

Y2J
Y2J원래의
2017-05-04 10:18:303793검색

Spring Boot는 Redis, MongoDB, Elasticsearch, Solr 및 Gemfire에 대한 자동 구성을 제공합니다. 이 기사에서는 springboot의 다중 redis 연결 구성에 대해 자세히 소개합니다. 관심 있는 사람은 더 자세히 알아볼 수 있습니다.

1. Springboot nosql 소개

Spring Data는 MongoDB, Neo4J, Elasticsearch, Solr, Redis, Gemfire, Couchbase 및 Cassandra. Spring Boot는 Redis, MongoDB, Elasticsearch, Solr 및 Gemfire에 대한 자동 구성을 제공합니다. 다른 프로젝트를 최대한 활용할 수 있지만 직접 구성해야 합니다.

1.1, Redis

Redis는 풍부한 기능을 갖춘 캐시, 메시지 미들웨어 및 키-값 저장 시스템입니다. Spring Boot는 Jedis 클라이언트 라이브러리와 Spring Data Redis에서 제공하는 Jedis 클라이언트 기반 추상화에 대한 자동 구성을 제공합니다. spring-boot-starter-redis 'Starter POM'은 종속성을 수집하는 편리한 방법을 제공합니다.
Redis는 maven 종속성을 추가합니다

   <dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-test</artifactId> 
  <scope>test</scope> 
</dependency> 
<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter</artifactId> 
  <!-- <version>1.3.5.RELEASE</version> --> 
</dependency> 
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons --> 
<dependency> 
  <groupId>org.springframework.boot</groupId> 
  <artifactId>spring-boot-starter-redis</artifactId> 
  <!-- <version>1.3.6.RELEASE</version> --> 
</dependency>

1.2 Redis 연결

자동으로 구성된 RedisConnectionFactory, StringRedisTemplate 또는 다른 Spring과 동일한 일반 RedisTemplate 인스턴스를 주입할 수 있습니다. 콩. 기본적으로 이 인스턴스는 localhost:6379를 사용하여 Redis 서버에 연결을 시도합니다.

@Component 
public class MyBean { 
private StringRedisTemplate template; 
@Autowired 
public MyBean(StringRedisTemplate template) { 
this.template = template; 
} 
// ... 
}

자동 구성된 유형 중 자신만의 @Bean을 추가하면 기본 @Bean이 대체됩니다(단, RedisTemplate의 경우는 예외입니다. RedisTemplate은 빈 이름이 아닌 'redisTemplate'에 따라 제외됩니다. 유형). commons-pool2가 클래스 경로에 존재하면 기본적으로 연결 풀 팩토리를 얻게 됩니다.

1.3 다중 Redis 연결 설정

redis 기본 구성을 사용하면 redis에서 0 라이브러리에 연결할 수 있습니다. indexdb를 구성해야 합니다. 동시에 여러 Redis 서비스를 연결해야 하는 경우 여러 데이터 소스도 동시에 구성해야 합니다.

1.3.1 application.yml에 다음을 추가합니다. 파일:

@Component 
public class MyBean { 
private StringRedisTemplate template; 
@Autowired 
public MyBean(StringRedisTemplate template) { 
this.template = template; 
} 
// ... 
}

1.3.2.redisconfiguration

@Configuration 
public class Redis137_11Configuration { 
 
  @Bean(name = "redis123Template") 
  public StringRedisTemplate redisTemplate( 
      @Value("${redis123.hostName}") String hostName, 
      @Value("${redis123.port}") int port, 
      @Value("${redis123.password}") String password, 
      @Value("${redis123.maxIdle}") int maxIdle, 
      @Value("${redis123.maxTotal}") int maxTotal, 
      @Value("${redis123.index}") int index, 
      @Value("${redis123.maxWaitMillis}") long maxWaitMillis, 
      @Value("${redis123.testOnBorrow}") boolean testOnBorrow) { 
    StringRedisTemplate temple = new StringRedisTemplate(); 
    temple.setConnectionFactory(connectionFactory(hostName, port, password, 
        maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow)); 
 
    return temple; 
  } 
 
  public RedisConnectionFactory connectionFactory(String hostName, int port, 
      String password, int maxIdle, int maxTotal, int index, 
      long maxWaitMillis, boolean testOnBorrow) { 
    JedisConnectionFactory jedis = new JedisConnectionFactory(); 
    jedis.setHostName(hostName); 
    jedis.setPort(port); 
    if (!StringUtils.isEmpty(password)) { 
      jedis.setPassword(password); 
    } 
    if (index != 0) { 
      jedis.setDatabase(index); 
    } 
    jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, 
        testOnBorrow)); 
    // 初始化连接pool 
    jedis.afterPropertiesSet(); 
    RedisConnectionFactory factory = jedis; 
 
    return factory; 
  } 
 
  public JedisPoolConfig poolCofig(int maxIdle, int maxTotal, 
      long maxWaitMillis, boolean testOnBorrow) { 
    JedisPoolConfig poolCofig = new JedisPoolConfig(); 
    poolCofig.setMaxIdle(maxIdle); 
    poolCofig.setMaxTotal(maxTotal); 
    poolCofig.setMaxWaitMillis(maxWaitMillis); 
    poolCofig.setTestOnBorrow(testOnBorrow); 
    return poolCofig; 
  } 
}

1.3.3.redis 추상 기본 클래스를 선언하고 redis 작업 메서드를 생성합니다

public abstract class AbRedisConfiguration { 
  protected StringRedisTemplate temple; 
 
  public void setData(String key, String value) { 
    getTemple().opsForValue().set(key, value); 
  } 
 
  public String getData(String key) { 
    return getTemple().opsForValue().get(key); 
  } 
 
  public StringRedisTemplate getTemple() { 
    return temple; 
  } 
}

1.3.4. 데이터 소스에 따라 다른 하위 클래스 @Component

public class Redis123 extends AbRedisConfiguration { 
 
  @Resource(name = "redis123Template") 
  private StringRedisTemplate temple; 
 
  public StringRedisTemplate getTemple() { 
    return temple; 
  } 
}

ps: getTemple 메서드와 StringRedisTempleattribute는 모두 클래스와 하위 클래스에서 선언됩니다. 하위 클래스는 하위 클래스의 자체 StringRedisTemple 속성을 상위 클래스에 전달합니다. 상위 클래스의 getTeimple 메소드를 재정의하여 클래스를 대체하고, 상위 클래스는 이를 하위 클래스를 통해 전달합니다. StringRedisTemple은 캐시를 작동하기 위해 다른 데이터 링크를 사용합니다. 이 시점에서 상위 클래스는 모든 작업 메서드를 완료했으며 데이터베이스 연결을 생성해야 할 때 하위 클래스를 생성하고 자체 StringRedisTemple을 선언한 후 상위 클래스에 전달하기만 하면 됩니다.

위 내용은 springboot가 여러 redis 연결을 구성하는 방법에 대한 심층 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.