본문 바로가기
DB

REDIS

by 공부 안하고 싶은 사람 2021. 3. 20.
반응형
  • REmote DIctionary Server

  • 특징

    • NoSQL & Cache
    • 컬렉션지원 ( String, Bitmap, Hash, List, Set, Sorted Set, Geospatial Index, Hyperloglog, Stream 등)
    • 삭제, exprires 설정하지 않으면 영속 보존
      • Snapshot : 특정 시점의 데이터를 복원
      • AOF : 로그를 읽어 write/update 순차적 복원
    • 실시간 처리는 인메모리, 보관은 디스크 기반 스토리지로
  • 용도

    • Message Queue (pub/sub 구조)
    • Shared Memory (session store)
    • Remote Dictionary (in-memory cache)
  • 레디스는 싱글 스레드 이므로 트랜잭션 문제 해결
    단, 저장된 모든 키를 보여주는 명령어(keys)나 모든 데이터를 소거하는 명령어(flushall) 금지

  • 아키텍쳐

    • 레디스센티넬 -> 마스터/슬레이브 구조
    • 샤딩
    • 클러스터(M/S + sharding)
  • 설정
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>
spring.redis:
    host: 
    port: 
    password: 
@Configuration
public class RedisConfig {
    @Value("${spring.redis.host}")
    private String redisHost;
    @Value("${spring.redis.port}")
    private int redisPort;
    @Value("${spring.redis.password}")
    private String redisPassword;

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(redisHost, redisPort);
        redisStandaloneConfiguration.setPassword(RedisPassword.of(redisPassword));
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

    @Bean // 이후 RedisTemplate<String, Object> 통해 레디스 접근가능
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        return redisTemplate;
    }
}
@Component
public class RedisLoadClientInfoSchedule {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private RedisClientDao redisCliendDao;

    private Map<String, RedisClientInfo> clientMap;

    private ImcLogger logger = ImcLoggerFactory.getInstance(this.getClass());

    @PostConstruct
    public void init() {
        redisCliendDao = new RedisClientDao(stringRedisTemplate);
        clientMap = new ConcurrentHashMap<>();
        load();
    }

    @Scheduled(cron = "${imc.channel.infobip.scheduled.redis-load-client-info}")
    public void load() {
        DateTime startTime = DateTime.now();
        Map<Object, Object> tmpClientMap = null;
        Map<String, RedisClientInfo> tmpRedisClientInfoMap = null;
        RedisClientInfo tmpRedisClientInfo = null;

        tmpClientMap = redisCliendDao.findAll();
        if (tmpClientMap != null && tmpClientMap.size() > 0) {
            tmpRedisClientInfoMap = new HashMap<>();

            for (Object clientId : tmpClientMap.keySet()) {
                tmpRedisClientInfo = RedisClientDao.convertToObject((String) tmpClientMap.get(clientId));
                tmpRedisClientInfoMap.put((String) clientId, tmpRedisClientInfo);
            }

            synchronized (clientMap) {
                for (String key : tmpRedisClientInfoMap.keySet()) {
                    clientMap.put(key, tmpRedisClientInfoMap.get(key));
                }
            }
        }
        logger.info("[Redis-Load] clientInfo. total: {}, elapsed time: {}", clientMap.size(),
                new Period(startTime, DateTime.now()));
    }

    @Bean(name = "clientMap") // 레디스 정보 bean으로 등록
    public Map<String, RedisClientInfo> clientMap() {
        return clientMap;
    }
}
728x90
반응형

'DB' 카테고리의 다른 글

Spring Boot에서 Redis를 기본적인 Cache(spring-boot-starter-cache)로 사용하기  (0) 2021.08.02
MsSQL Shrink  (0) 2021.02.25
NoSQL  (0) 2021.02.03

댓글