2017-11-15 14 views
0

AWS를 시작하기 시작했으며 Spring과 함께 Redis-jedis에서 AWS ElasticCache를 사용해야한다는 요구 사항이 있습니다. 봄 - 데이터 - 레디 스 1.8.8.RELEASE AWS-자바 SDK 1.11.228 봄 4.2.9.RELEASE jedisAccess ElasticCache - Jedis 및 spring

2.9.0 I 연결할 수 있었다 및 코드 아래 로컬 레디 스에 캐시 데이터 . 코드 변경을 https://github.com/fishercoder1534/AmazonElastiCacheExample/tree/master/src/main/java으로 시도했지만 성공하지 못했습니다. 몇 가지 샘플 코드에 대해 도움이되고 도움이 될 것입니다. AWS ElasticCache는 현재 옵션 1로 구성되어 있지만 곧 옵션 2로 이동해야합니다. 1. 복제되지 않은 클러스터 - 복제본이없는 Redis 클러스터 비활성화 됨 2. 복제 된 클러스터 - 읽기 복제본으로 Redis 클러스터 사용 및 Redis 클러스터가 비활성화되었습니다.

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.beans.factory.annotation.Value; 
import org.springframework.cache.CacheManager; 
import org.springframework.cache.annotation.CachingConfigurerSupport; 
import org.springframework.cache.annotation.EnableCaching; 
import org.springframework.context.annotation.Bean; 
import org.springframework.context.annotation.Configuration; 
import org.springframework.context.annotation.PropertySource; 
import org.springframework.data.redis.cache.RedisCacheManager; 
import org.springframework.data.redis.connection.RedisConnectionFactory; 
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; 
import org.springframework.data.redis.core.RedisTemplate; 
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; 
import org.springframework.data.redis.serializer.StringRedisSerializer; 
import redis.clients.jedis.Jedis; 
import org.springframework.cache.interceptor.KeyGenerator; 
import java.lang.reflect.Method; 
import java.util.List; 

@Configuration 
@EnableCaching 
// @PropertySource("classpath:/redis.properties") 
public class CacheConfig extends CachingConfigurerSupport { 
// private @Value("${redis.host}") String redisHost; 
// private @Value("${redis.port}") int redisPort; 

//@Bean 
    public KeyGenerator keyGenerator() { 
    return new KeyGenerator() { 
     @Override 
     public Object generate(Object o, Method method, Object... objects) { 
     // This will generate a unique key of the class name, the method name, and all method parameters appended. 
     StringBuilder sb = new StringBuilder(); 
     sb.append(o.getClass().getName()); 
     sb.append(method.getName()); 
     for (Object obj : objects) { 
      sb.append(obj.toString()); 
     } 
     return sb.toString(); 
     } 
    }; 
    } 


@Bean 
public JedisConnectionFactory redisConnectionFactory() { 
    JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(); 

    // Defaults for redis running on Local Docker 
    redisConnectionFactory.setHostName("192.168.99.100"); 
    redisConnectionFactory.setPort(6379); 

    return redisConnectionFactory; 
} 

@Bean 
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) { 
    RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); 
    redisTemplate.setConnectionFactory(cf); 
    redisTemplate.setDefaultSerializer(new JdkSerializationRedisSerializer()); 
    return redisTemplate; 
} 

@Bean 
public CacheManager cacheManager(RedisTemplate<String, String> redisTemplate) { 
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); 

    // Number of seconds before expiration. Defaults to unlimited (0) 
    cacheManager.setDefaultExpiration(1200); 
    cacheManager.getCacheNames().forEach(cacheM-> {System.out.println(cacheM);}); 
    return cacheManager; 
} 

}

답변

1
AWS 탄성 캐시 + 추 (레디 스 자바 클라이언트) + 스프링 데이터 레디 스 구현과

캐싱. Spring @Cachable 및 @CacheEvict 주석을 사용하여 2 개의 슬레이브 및 SSL을 사용하는 3 개의 마스터 문제가 있거나 더 나은 방법으로 해결할 수 있다면 모든 의견을 제공해주십시오.

Spring 4.3.12.RELEASE 
Spring-data-redis 1.8.8.RELEASE 
aws-java-sdk 1.11.228 
Lettuce (Redis java Client) 4.4.2.Final 

@Configuration 
@EnableCaching 
public class CacheConfig extends CachingConfigurerSupport { 
long expirationDate = 1200; 

static AWSCredentials credentials = null; 
static { 
    try { 
     //credentials = new ProfileCredentialsProvider("default").getCredentials(); 
     credentials = new SystemPropertiesCredentialsProvider().getCredentials(); 
    } catch (Exception e) { 
     System.out.println("Got exception.........."); 
     throw new AmazonClientException("Cannot load the credentials from the credential profiles file. " 
       + "Please make sure that your credentials file is at the correct " 
       + "location (/Users/USERNAME/.aws/credentials), and is in valid format.", e); 
    }  
} 

@Bean 
public LettuceConnectionFactory redisConnectionFactory() { 
    AmazonElastiCache elasticacheClient = AmazonElastiCacheClientBuilder.standard().withCredentials(new AWSStaticCredentialsProvider(credentials)).withRegion(Regions.US_EAST_1).build(); 
    DescribeCacheClustersRequest dccRequest = new DescribeCacheClustersRequest(); 
    dccRequest.setShowCacheNodeInfo(true); 

    DescribeCacheClustersResult clusterResult = elasticacheClient.describeCacheClusters(dccRequest); 

    List<CacheCluster> cacheClusters = clusterResult.getCacheClusters(); 
    List<String> clusterNodes = new ArrayList <String>(); 
    try { 
     for (CacheCluster cacheCluster : cacheClusters) { 
      for (CacheNode cacheNode : cacheCluster.getCacheNodes()) { 
       String addr = cacheNode.getEndpoint().getAddress(); 
       int port = cacheNode.getEndpoint().getPort(); 
       String url = addr + ":" + port; 
       if(<CLUSTER NAME>.equalsIgnoreCase(cacheCluster.getReplicationGroupId())) 
        clusterNodes.add(url); 
      } 
     } 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    }  
    LettuceConnectionFactory redisConnectionFactory = new LettuceConnectionFactory(new RedisClusterConfiguration(clusterNodes)); 
    redisConnectionFactory.setUseSsl(true); 
    redisConnectionFactory.afterPropertiesSet(); 
    return redisConnectionFactory; 
} 

    @Bean 
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) { 
    RedisTemplate<String, String> redisTemplate = new RedisTemplate<String, String>(); 
    redisTemplate.setConnectionFactory(cf); 
    redisTemplate.setDefaultSerializer(new JdkSerializationRedisSerializer()); 
    return redisTemplate; 
} 

@Bean 
public CacheManager cacheManager(RedisTemplate<String, String> redisTemplate) { 
    RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate); 

    // Number of seconds before expiration. Defaults to unlimited (0) 
    cacheManager.setDefaultExpiration(expirationDate); 
    cacheManager.setLoadRemoteCachesOnStartup(true); 
    return cacheManager; 
} 

}