개발
Redis 트랜잭션, Spring Data Redis
ka0oll
2020. 3. 31. 09:43
redis 트랜잭션
-
redis는 트랜잭션을 지원한다.
-
실행될 항목들을 QUEUE넣고 한번에 순차적 실행한다.
//reids cli > MULTI //트랜잭션 시작 OK > INCR foo QUEUED > INCR bar QUEUED > EXEC //트랜잭션 종료 1) (integer) 1 2) (integer)
-
EXEC 이후 발생한 오류는 특별한 방법으로 처리되지 않습니다. 트랜잭션 중에 일부 명령이 실패하더라도 다른 모든 명령들이 실행됩니다.
-
롤백 미지원
- 실패는 오직 syntax에러만, 잘못된 타입 접근
- 결국 프로그래밍 오류로만 도중 에러가 발생한다.
- 롤백이 없기 때문에 속도가 빠르다.
- 실패는 오직 syntax에러만, 잘못된 타입 접근
spring data redis?
스프링에서 redis를 사용하기 쉽게, 설정 코드 같은 것들을 간결하게 해준다.
https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#reference
spring redis 트랜잭션
RedisTemplate 이용한 트랜잭션
//execute a transaction
List<Object> txResults = redisTemplate.execute(new SessionCallback<List<Object>>() {
public List<Object> execute(RedisOperations operations) throws DataAccessException {
operations.multi();
operations.opsForSet().add("key", "value1");
// This will contain the results of all operations in the transaction
return operations.exec();
}
});
System.out.println("Number of items added to set: " + txResults.get(0));
@Trascational 어노테이션 이용
@Bean
public StringRedisTemplate redisTemplate() {
StringRedisTemplate template = new StringRedisTemplate(redisConnectionFactory());
// explicitly enable transaction support
template.setEnableTransactionSupport(true);
return template;
}
redis repository
사용 조건
- Redis Server version 2.8.0 이상
- 트랜잭션은 지원하지 않는다.
왜사용하냐??
- 도메인 객체를 쉽게 변환하고 저장 할수도 있도록 해준다.
- RedisTemplate를 사용시 직접 json으로 만들어서 해야 되지만, 쉽게 저장할수있고, 조회 가능하다.
- 도메인 주도적으로 개발시 매우 유용하다.
적용 방식
- redis의 hash 데이터 타입을 이용해 저장한다. keyspace:{id} => people:{idT}
- TTL도 줄수 있다.
- setter없이도 필드 셋팅 가능
@RedisHash("people" , timeToLive= "1000")//ttl
public class Person {
@Id String id;
String firstname;
String lastname;
Address address;
}
//redis
_class = org.example.Person
id = e2c7dcee-b8cd-4424-883e-736ce564363e
firstname = rand
lastname = al’thor
address = { city : "emond's field", country : "andor" }
public class TimeToLiveOnMethod {
@Id
private String id;
@TimeToLive //이렇게 ttl가능
public long getTimeToLive() {
return new Random().nextLong();
}
}
repository
- crudRepository 상속, 기본적인 crud지원
public interface PersonRepository extends CrudRepository<Person, String> {
}
secondIndex 지원
- index key : db 인덱스처럼 실제 데이터 레퍼런스
@RedisHash("people")
public class Person {
@Id String id;
@Indexed String firstname;
String lastname;
Address address;
}
new Person("id", "aviendha");
//redis-cli
people:id //hash type
people:firstname:aviendha -> people:id // sets type(디비 인덱스처럼 여러개를 가리킨다)