티스토리 뷰

1. pom.xml 에 다음의 디펜던시(dependency)를 추가한다.

<!-- redis support -->
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.5.7</version>
</dependency>




2. 환경설정 (config setup)

application.yml 파일에 아래와 같이 redis 컨피그를 설정한다.

redis가 1개라면 싱글, 여러개라면 클러스터 또는 엘라스틱캐시를 사용한다.

또한 1개라면 nodes 에 하나만 적어주면 되고, 여러개라면 - "redis://111.222.333.444:6379" 이런식으로 추가해주면 된다. (물론 mode 도 변경해야 한다.)

redis:
# single, cluster, elasticcache:
mode: single
nodes:
- "redis://localhost:6379"




3. 초기화 (RedisConfiguration.java) 파일 생성.

@Component
@ConfigurationProperties("redis")
public class RedisConfiguration {

private String mode = "single";
private String password = null;
private List<String> nodes;

public String getMode() {
return mode;
}

public void setMode(String mode) {
this.mode = mode;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public List<String> getNodes() {
return nodes;
}

public void setNodes(List<String> nodes) {
this.nodes = nodes;
}

}




4. 빌더(RedisClientBuilder.java) 파일 생성

public class RedisClientBuilder {

public static RedissonClient buildRedissionClient(RedisConfiguration rc) {
Config config = new Config().setCodec(StringCodec.INSTANCE);
if ("single".equals(rc.getMode())) {
SingleServerConfig ssc = config.useSingleServer();
ssc.setAddress(rc.getNodes().get(0));
if (rc.getPassword() != null) {
ssc.setPassword(rc.getPassword());
}
return Redisson.create(config);
} else if ("cluster".equals(rc.getMode())) {
ClusterServersConfig csc = config.useClusterServers();
rc.getNodes().forEach(node -> {
csc.addNodeAddress(node);
});
if (rc.getPassword() != null) {
csc.setPassword(rc.getPassword());
}
return Redisson.create(config);
}
throw new IllegalArgumentException("Invalid mode: " + rc.getMode());
}
}




5. Bean 등록

필자의 경우 스프링 부트 2.0.4를 사용하고 있고 Bean 으로 등록하였다.

@Bean
public RedissonClient createRedisClient(@Autowired RedisConfiguration rc) {
return RedisClientBuilder.buildRedissionClient(rc);
}




6. 사용 예

6-1. 의존성 주입

@Autowired
RedissonClient redisClient;


6-2. 함수 생성

private void checkAESKey() {
logger.debug("AES Enc/Dec Key Check!");
String checkStr = (String) redisClient.getBucket("AESKey").get();

if(checkStr == null || "".equals(checkStr)) {
logger.debug("AES Key does not exist in redis cache. Gets the key value from DB.");
Algorithm alg = cryptoRepository.findAlgorithmByAlgName("AES256");
this.AESKey = alg.getAESKey();
iv = alg.getAESKey().substring(0, 16);

redisClient.getBucket("AESKey").set(alg.getAESKey());
} else {
logger.debug("Found AES Key in redis cache");
this.AESKey = checkStr;
this.iv = this.AESKey.substring(0, 16);
}
}


필자의 경우 AES 암복호화 키를 가져오는 부분에 redis를 연동하였다.


동작 순서는 다음과 같다.


1. redissonclient 객체를 통해서 redis 에 "AESKey"라는 이름(key)값으로 등록된 값이 있는지 체크한다.

String checkStr = (String) redisClient.getBucket("AESKey").get();


if(checkStr == null || "".equals(checkStr))



2. 체크 결과 값(value)이 없다면  DB에 저장된 AESKey 값을 가져온다.

Algorithm alg = cryptoRepository.findAlgorithmByAlgName("AES256");


# 참고로 Algorithm 객체는 필요에 의해 만들었다. 구조는 다음과 같다.

@Entity
@Getter
@Setter
@Table(name = "crypto", uniqueConstraints = @UniqueConstraint(name = "ALGNAME", columnNames = { "algName" }))
public class Algorithm implements EntitySupport {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(nullable = false, updatable = false, length = VAR_ENUM)
public long id;

@Column(nullable = false, length = 100)
public String algName;

@Column(nullable = false, length = 32)
public String AESKey;

@Column(nullable = false, updatable = false)
@CreatedDate
public long createdAt;

} 


JPA 를 사용하고 있다.


3. 만약 redis에 "AESKey"라는 이름(Key) 으로 등록된 것이 있다면 해당 키 값을 사용한다.

 } else {

logger.debug("Found AES Key in redis cache");
this.AESKey = checkStr;
this.iv = this.AESKey.substring(0, 16);
}






### 요약 ###

1. redissonclient 객체를 생성한다.

2. 이름 / 값(key / value) 을 등록하려면 redisclient.getBucket("키").set("값"); 

3. 이름(key) 를 통해 값을 조회하려면(=가져오려면) redisclient.getBucket("키").get();

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함