Redis๋ฅผ ํ์ฉํ ์ค์๊ฐ ๋ญํน ๊ตฌํ! (์งง๊ณ ๊ฐ๋จํ ์์)
์ญ์๋ ๋ ๋์ค ๊ณต๋ถํ ๊ฒ ๊น๋จน๊ธฐ ์ซ์ด ๊ธฐ๋ก์ผ๋ก ๋จ๊ธด๋ค.
๋์์
์์ค
application.yml
server:
port: 8081
servlet:
context-path: /
encoding:
charset: UTF-8
enabled: true
force: true
spring:
cache:
type: redis
devtools:
livereload.enabled: true
restart.enabled: true
datasource:
driver-class-name: net.sf.log4jdbc.sql.jdbcapi.DriverSpy
url: jdbc:log4jdbc:mysql://localhost:3309/db๋ช
hikari:
username: ์ฌ์ฉ์
password: ๋น๋ฐ๋ฒํธ
connectionTimeout: 10000
maximum-pool-size: 15
max-lifetime: 600000
readOnly: false
connection-test-query: SELECT 1
jpa:
hibernate:
ddl-auto: update #create update none
naming:
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
show-sql: true
# Redis ์ค์ ์ถ๊ฐ
data:
redis:
host: localhost # Redis ์๋ฒ ์ฃผ์
port: 6379 # Redis ํฌํธ
password: # (ํ์ํ๋ฉด ๋น๋ฐ๋ฒํธ ์ถ๊ฐ)
timeout: 6000 # ์ฐ๊ฒฐ ํ์์์ (ms)
lettuce:
pool:
max-active: 8 # ์ต๋ ํ์ฑ ์ฐ๊ฒฐ ์
max-idle: 8 # ์ต๋ ์ ํด ์ฐ๊ฒฐ ์
min-idle: 0 # ์ต์ ์ ํด ์ฐ๊ฒฐ ์
max-wait: -1 # ์ต๋ ๋๊ธฐ ์๊ฐ (๋ฌด์ ํ)
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '3.3.9'
id 'io.spring.dependency-management' version '1.1.7'
}
group = 'com.lsy'
version = '0.0.1-SNAPSHOT'
java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
}
}
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'org.springframework.boot:spring-boot-starter-web'
// Logging
implementation 'org.bgee.log4jdbc-log4j2:log4jdbc-log4j2-jdbc4.1:1.16'
// swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.2'
// redis
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
compileOnly 'org.projectlombok:lombok'
runtimeOnly 'com.mysql:mysql-connector-j'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}
tasks.named('test') {
useJUnitPlatform()
}
RedisConfig
package com.lsy.realtimetest1.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableCaching
public class RedisConfig {
@Value("${data.redis.host}")
private String host;
@Value("${data.redis.port}")
private int port;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(host, port);
}
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
return redisTemplate;
}
}
controller
package com.lsy.realtimetest1.controller;
import com.lsy.realtimetest1.service.RankService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/rank")
@RequiredArgsConstructor
public class RankController {
private final RankService service;
// ์ ์ ์ถ๊ฐ API
@PostMapping("/add")
public void addScore(@RequestParam String player, @RequestParam double score) {
service.addScore(player, score);
}
// ์ ์ ์ฆ๊ฐ API
@PostMapping("/increase")
public void increaseScore(@RequestParam String player, @RequestParam double score) {
service.increaseScore(player, score);
}
// ์์ ๋ญํน ์กฐํ API
@GetMapping("/top")
public List<String> getTopPlayers(@RequestParam(defaultValue = "10") int limit) {
return service.getTopPlayers(limit);
}
// ํน์ ํ๋ ์ด์ด ์์ ์กฐํ API
@GetMapping("/rank")
public Long getPlayerRank(@RequestParam String player) {
return service.getPlayerRank(player);
}
}
service
package com.lsy.realtimetest1.service;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
@Slf4j
public class RankService {
private final RedisTemplate redisTemplate;
private final String leaderboardKey = "rank";
// ์ ์ ์ถ๊ฐ (ZADD)
public void addScore(String player, double score) {
String playerKey = "rank:" + player; // playerID์ "rank:" ์ ๋์ด ์ถ๊ฐ
redisTemplate.opsForZSet().add(leaderboardKey, playerKey, score);
}
// ์ ์ ์ฆ๊ฐ (ZINCRBY)
public void increaseScore(String player, double score) {
String playerKey = "rank:" + player; // playerID์ "rank:" ์ ๋์ด ์ถ๊ฐ
redisTemplate.opsForZSet().incrementScore(leaderboardKey, playerKey, score);
}
// ์์ ๋ญํน ์กฐํ (ZREVRANGE WITHSCORES)
public List<String> getTopPlayers(int limit) {
Set<ZSetOperations.TypedTuple<String>> orgResult =
redisTemplate.opsForZSet().reverseRangeWithScores(leaderboardKey, 0, limit - 1);
return orgResult.stream()
.map(tuple -> tuple.getValue().replace("rank:", "") + " (Score: " + tuple.getScore() + ")")
.collect(Collectors.toList());
}
// ํน์ ํ๋ ์ด์ด์ ์์ ์กฐํ (ZRANK)
public Long getPlayerRank(String player) {
String playerKey = "rank:" + player;
Long rank = redisTemplate.opsForZSet().reverseRank(leaderboardKey, playerKey);
return (rank != null) ? rank + 1 : null; // 0๋ถํฐ ์์ → 1๋ถํฐ ์์ํ๋๋ก ๋ณํ ๋ณํ
}
}
๊ฐ์ธ ์คํฐ๋ ๊ธฐ๋ก์ ๋ฉ๋ชจํ๋ ๊ณต๊ฐ์ด๋ผ ํ๋ฆฐ์ ์ด ์์ ์ ์์ต๋๋ค.
ํ๋ฆฐ ์ ์์ ๊ฒฝ์ฐ ๋๊ธ ๋ถํ๋๋ฆฝ๋๋ค.
Spring Boot + Redis๋ก ์ธ์ ๊ณต์ ํ๊ธฐ (ํ ์คํธ ์์ & ์์ค ์ฝ๋ ํฌํจ)
Redis๋ฅผ ํ์ฉํ ์ ํ๋ฆฌ์ผ์ด์ ๊ฐ ์ธ์ ๊ณต์ ์คํ! (์งง๊ณ ๊ฐ๋จํ ์์)๋ ๋์ค๋ฅผ ๊ณต๋ถํ์ง ์ผ๋ง ์๋์ด์ ๊น๋จน๊ธฐ ์ซ์ด ๊ธฐ๋ก์ผ๋ก ๋จ๊ธด๋ค.๋์์์์คapplication.ymlserver: port: 9090 servlet: context-path: / encodin
yaga.tistory.com
Spring Boot + Redis ์บ์ฑ ๊ตฌํํ๊ธฐ (ํ ์คํธ ์์ & ์์ค ์ฝ๋ ํฌํจ)
Redis๋ฅผ ํ์ฉํ ์บ์ฑ ๊ตฌํ! (์งง๊ณ ๊ฐ๋จํ ์์)์ญ์๋ ๋ ๋์ค ๊ณต๋ถํ ๊ฒ ๊น๋จน๊ธฐ ์ซ์ด ๊ธฐ๋ก์ผ๋ก ๋จ๊ธด๋ค.๋์์์์คapplication.ymlserver: port: 9090 servlet: context-path: / encoding: charset: UTF-8 enabled: true force: tru
yaga.tistory.com
๋๊ธ