[Docker] docker-compose 이용해 redis 띄우기
IntelliJ
build.gradle
dependencies {
...
// Redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'redis.clients:jedis:3.3.0'
}
application.yml
spring:
redis:
host: redis
port: 6379
docker-compose.yml
version: '3'
services:
redis:
image: redis:alpine
command: redis-server --port 6379
container_name: redis_db
# hostname: redis_db
labels:
- "name=redis"
- "mode=standalone"
ports:
- "6379:6379"
redisConfig.java
@Configuration
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(host);
redisStandaloneConfiguration.setPort(port);
return new LettuceConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory());
return redisTemplate;
}
}
redisController.java
@RestController
@RequestMapping("/redis")
public class RedisController {
private final RedisTemplate<String, String> redisTemplate;
@Autowired
public RedisController(RedisTemplate<String, String> redisTemplate) {
this.redisTemplate = redisTemplate;
}
// set
@PostMapping("")
public String setRedisKey(@RequestBody Map<String, String> req){
ValueOperations<String, String> vop = redisTemplate.opsForValue();
try {
// Redis Set Key-value
vop.set(req.get("key").toString(), req.get("value").toString());
return "set message success";
} catch (Exception e) {
return "set message fail";
}
}
// get
@GetMapping("/{key}")
public String getRedisKey(@PathVariable String key) {
ValueOperations<String, String> vop = redisTemplate.opsForValue();
return vop.get(key);
}
}
EC2 인스턴스 접속
# 빌드
$ docker-compose up --build
# 실행
$ docker-compose up -d
Ref
- https://velog.io/@armton/Docker-Springboot-Redis-%EC%97%B0%EB%8F%99
- https://basketdeveloper.tistory.com/85
💛 개인 공부 기록용 블로그입니다. 👻