부트 개념과 활용-27.Redis(스프링 데이터)
스프링 데이터 9부: Redis
캐시, 메시지 브로커, 키/밸류 스토어 등으로 사용 가능.
의존성 추가
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Redis 설치 및 실행 (도커)
- docker run -p 6379:6379 –name redis_boot -d redis
- docker exec -i -t redis_boot redis-cli
스프링 데이터 Redis
- https://projects.spring.io/spring-data-redis/
- StringRedisTemplate 또는 RedisTemplate
- extends CrudRepository
예제 코드
@RedisHash("accounts")
public class Account {
@Id
private String id;
private String username;
private String email;
...
public interface AccountRepository extends CrudRepository<Account, String> {
}
@Component
public class RedisRunner implements ApplicationRunner {
@Autowired
StringRedisTemplate redisTemplate;
@Autowired
AccountRepository accountRepository;
@Override
public void run(ApplicationArguments args) throws Exception {
ValueOperations<String, String> values = redisTemplate.opsForValue();
values.set("jaeuk", "me");
values.set("springboot", "2.0");
values.set("hello", "world");
Account account = new Account();
account.setEmail("jaeuk2274@gmail.com");
account.setUsername("jaeuk");
accountRepository.save(account);
Optional<Account> byId = accountRepository.findById(account.getId());
System.out.println(byId.get().getUsername());
System.out.println(byId.get().getEmail());
}
}
Redis 주요 커맨드
- https://redis.io/commands
- keys *
- get {key}
- hgetall {key}
- hget {key} {column}
127.0.0.1:6379> keys *
1) "accounts"
2) "hello"
3) "accounts:9318f778-b15c-4f3d-ae72-365e751849bc"
4) "jaeuk"
5) "springboot"
127.0.0.1:6379> get hello
"world"
127.0.0.1:6379> hget accounts:9318f778-b15c-4f3d-ae72-365e751849bc email
"jaeuk2274@gmail.com"
127.0.0.1:6379> hgetall accounts:9318f778-b15c-4f3d-ae72-365e751849bc
1) "_class"
2) "me.jaeuk.redis.account.Account"
3) "id"
4) "9318f778-b15c-4f3d-ae72-365e751849bc"
5) "username"
6) "jaeuk"
7) "email"
8) "jaeuk2274@gmail.com"
127.0.0.1:6379>
커스터마이징 spring.redis.*
ex.
#spring.redis.url=