Skip to content

Commit

Permalink
Merge pull request #143 from TEAMMatchDev/feature/issue-104
Browse files Browse the repository at this point in the history
[Refactor] Redis - PROD, DEV 서버 통일
  • Loading branch information
imenuuu authored Nov 6, 2023
2 parents f7c682b + 7813b6f commit ab3c0b1
Show file tree
Hide file tree
Showing 13 changed files with 89 additions and 50 deletions.
89 changes: 56 additions & 33 deletions .github/workflows/batch_api_ci_cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ name: Match batch Server CI/CD
on:
push:
branches: [batch]
#tags:
# - Dev-Api-v*.*.*
workflow_dispatch: # 수동 실행 옵션 (생략)

jobs:
Expand All @@ -21,48 +19,78 @@ jobs:
java-version: '11'
distribution: 'temurin'

- name: Set Environment - Common Yml
- name: Set Environment - Common Prod Yml
uses: microsoft/variable-substitution@v1
with:
files: ./Match-Common/src/main/resources/application-common.yml
env:
oauth.kakao.base-url: ${{ secrets.KAKAO_BASE_URL }}
oauth.kakao.base-url: ${{ secrets.KAKAO_PROD_BASE_URL }}
oauth.kakao.client-id: ${{ secrets.KAKAO_CLIENT }}
oauth.kakao.client-secret: ${{ secrets.KAKAO_SECRET }}
oauth.kakao.redirect-url: ${{ secrets.KAKAO_REDIRECT }}
oauth.kakao.redirect-url: ${{ secrets.KAKAO_PROD_REDIRECT }}
oauth.kakao.app-id: ${{ secrets.KAKAO_APP_ID }}
oauth.kakao.admin-key: ${{ secrets.KAKAO_ADMIN_KEY }}
jwt.secret: ${{ secrets.JWT_SECRET_KEY }}
jwt.refresh: ${{ secrets.JWT_REFRESH_KEY }}
oauth.naver.secret: ${{ secrets.NAVER_SECRET }}
oauth.naver.client: ${{ secrets.NAVER_CLIENT }}
oauth.naver.redirect-url: ${{ secrets.NAVER_REDIRECT}}
oauth.naver.redirect-url: ${{ secrets.NAVER_PROD_REDIRECT}}
sms.secret: ${{ secrets.SMS_SECRET_KEY }}
sms.api: ${{ secrets.SMS_API_KEY }}
sms.sender: ${{ secrets.SMS_SENDER }}
nice.secret: ${{ secrets.NICE_SECRET_KEY}}
nice.client: ${{ secrets.NICE_CLIENT_KEY }}
nice.url: ${{ secrets.NICE_DEV_URL}}
nice.secret: ${{ secrets.NICE_PROD_SECRET_KEY}}
nice.client: ${{ secrets.NICE_PROD_CLIENT_KEY }}
nice.url: ${{ secrets.NICE_PROD_URL}}
aws.access-key: ${{ secrets.AWS_S3_ACCESS_KEY }}
aws.secret-key: ${{ secrets.AWS_S3_SECRET_KEY }}
aws.s3.bucket: ${{ secrets.AWS_S3_BUCKET }}
aws.s3.bucket-url: ${{ secrets.AWS_S3_BASE_URL }}
discord.webhook.error: ${{ secrets.DISCORD_WEBHOOK_ERROR}}
discord.webhook.alert: ${{ secrets.DISCORD_WEBHOOK_ALERT }}
web.return.url: ${{ secrets.PROD_RETURN_URL }}
match.aligo.url: ${ secrets.MATCH_ALIGO_URL }}
server.host: ${{ secrets.PROD_SERVER_HOST}}
spring.password: ${{ secrets.APP_PASSWORD}}
aligo.username: ${{ secrets.ALIGO_USERNAME }}
aligo.key: ${{ secrets.ALIGO_KEY }}
portone.code: ${{ secrets.PORTONE_CODE }}
portone.key: ${{ secrets.PORTONE_KEY }}
portone.secret: ${{ secrets.PORTONE_SECRET }}
portone.billmid: ${{ secrets.PROD_PORTONE_BILL_MID}}


- name: Set Environment Domain - Domain DEV Yml

- name: Set Environment Domain - Domain Prod Yml
uses: microsoft/variable-substitution@v1
with:
files: ./Match-Domain/src/main/resources/application-domain-dev.yml
files: ./Match-Domain/src/main/resources/application-domain-prod.yml
env:
spring.datasource.url: ${{ secrets.DB_URL_HOST }}
spring.datasource.username: ${{ secrets.AWS_DB_USER_NAME }}
spring.datasource.password: ${{ secrets.AWS_DB_PASSWORD }}
spring.redis.host : ${{ secrets.REDIS_DEV_HOST }}
spring.datasource.master.hikari.jdbc-url: ${{ secrets.PROD_DB_URL_HOST }}
spring.datasource.master.hikari.username: ${{ secrets.AWS_DB_USER_NAME }}
spring.datasource.master.hikari.password: ${{ secrets.AWS_DB_PASSWORD }}
spring.datasource.slave.hikari.jdbc-url: ${{ secrets.PROD_SLAVE_URL_HOST }}
spring.datasource.slave.hikari.username: ${{ secrets.AWS_DB_USER_NAME }}
spring.datasource.slave.hikari.password: ${{ secrets.AWS_DB_PASSWORD }}
spring.redis.host : ${{ secrets.REDIS_PROD_HOST }}

- name: create-fcm-json
id: create-fcm-json
uses: jsdaniell/[email protected]
with:
name: "serviceAccountKey.json"
json: ${{ secrets.FCM_JSON }}
dir: "Match-Common/src/main/resources/"

- name: Grant execute permission for gradlew
run: chmod +x ./gradlew
shell: bash

- name: Docker Login
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}

- name: Build with Gradle
run: ./gradlew Match-Batch:bootJar
shell: bash
Expand All @@ -74,23 +102,18 @@ jobs:
format: YYYYMMDDTHHmm
utcOffset: "+09:00"

- name: Generate deployment package
run: |
mkdir -p deploy
cp Match-Batch/build/libs/*.jar deploy/match-batch.jar
cp Procfile deploy/Procfile
cp -r .ebextensions-dev deploy/.ebextensions
cp -r .platform deploy/.platform
cd deploy && zip -r match-batch-${{steps.current-time.outputs.formattedTime}}-${{github.sha}} .
- name: Build and push Docker image
uses: docker/build-push-action@v2
with:
context: .
file: Dockerfile
push: true
tags: ${{ secrets.DOCKER_REPO }}/match_batch_image:latest

- name: Deploy Consumer to EB
uses: einaregilsson/beanstalk-deploy@v19
- name: trigger jenkins job.
uses: appleboy/jenkins-action@master
with:
aws_access_key: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws_secret_key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
application_name: match-batch
environment_name: Match-batch-env
version_label: match-batch-${{steps.current-time.outputs.formattedTime}}-${{github.sha}}
region: ap-northeast-2
deployment_package: deploy/match-batch-${{steps.current-time.outputs.formattedTime}}-${{github.sha}}.zip
wait_for_deployment: false
url: ${{ secrets.WEBHOOK_URL }}
user: "matchadmin"
token: ${{ secrets.JENKINS_API_TOKEN }}
job: "match-batch"
7 changes: 5 additions & 2 deletions .github/workflows/dev_api_ci_cd.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ name: dev MATCH API Server CI/CD
on:
push:
branches: [dev]
#tags:
# - Dev-Api-v*.*.*
workflow_dispatch: # 수동 실행 옵션 (생략)

jobs:
Expand Down Expand Up @@ -48,6 +50,7 @@ jobs:
discord.webhook.error: ${{ secrets.DISCORD_WEBHOOK_ERROR}}
discord.webhook.alert: ${{ secrets.DISCORD_WEBHOOK_ALERT }}
server.host: ${{ secrets.DEV_SERVER_HOST}}

spring.password: ${{ secrets.APP_PASSWORD}}
aligo.username: ${{ secrets.ALIGO_USERNAME }}
aligo.key: ${{ secrets.ALIGO_KEY }}
Expand All @@ -70,7 +73,7 @@ jobs:
spring.datasource.slave.hikari.jdbc-url: ${{ secrets.DEV_SLAVE_URL_HOST }}
spring.datasource.slave.hikari.username: ${{ secrets.AWS_DB_USER_NAME }}
spring.datasource.slave.hikari.password: ${{ secrets.AWS_DB_PASSWORD }}
spring.redis.host : ${{ secrets.REDIS_DEV_HOST }}
spring.redis.host : ${{ secrets.REDIS_PROD_HOST }}

- name: create-fcm-json
id: create-fcm-json
Expand Down Expand Up @@ -114,4 +117,4 @@ jobs:
version_label: match-server-api-${{steps.current-time.outputs.formattedTime}}-${{github.sha}}
region: ap-northeast-2
deployment_package: deploy/match-server-api-${{steps.current-time.outputs.formattedTime}}-${{github.sha}}.zip
wait_for_deployment: false
wait_for_deployment: false
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
FROM openjdk:11-jdk-slim
ADD /Match-Aligo/build/libs/*.jar app.jar
RUN apk add tzdata && ln -snf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
ADD /Match-Batch/build/libs/*.jar app.jar
ENTRYPOINT ["java","-jar","-Dspring.profiles.active=prod", "/app.jar"]
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@
import com.example.matchdomain.redis.entity.RefreshToken;
import com.example.matchdomain.redis.repository.AccessTokenRepository;
import com.example.matchdomain.redis.repository.RefreshTokenRepository;
import com.example.matchdomain.user.adaptor.UserAdaptor;
import com.example.matchdomain.user.entity.User;
import com.example.matchdomain.user.repository.UserRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
Expand All @@ -25,19 +28,18 @@
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.NoSuchElementException;
import java.util.Optional;

@RequiredArgsConstructor
@Component
@Slf4j
public class JwtService {


private final UserRepository userRepository;
private final JwtProperties jwtProperties;
private final RefreshTokenRepository refreshTokenRepository;
private final AccessTokenRepository accessTokenRepository;
private final UserAdaptor userAdaptor;


private Key getSecretKey() {
Expand Down Expand Up @@ -112,7 +114,9 @@ public Authentication getAuthentication(String token, ServletRequest servletRequ
.parseClaimsJws(token);

Long userId=claims.getBody().get("userId",Long.class);
Optional<User> users = userRepository.findById(userId);
log.info("user find");
Optional<User> users = userAdaptor.findByUserId(userId);
log.info("user find");
return new UsernamePasswordAuthenticationToken(users.get(),"",users.get().getAuthorities());
}catch(NoSuchElementException e){
servletRequest.setAttribute("exception","NoSuchElementException");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public CommonResponse<String> requestPayPrepare(
}

@PostMapping("/pay/card")
@ApiErrorCodeExample({UserAuthErrorCode.class, OtherServerErrorCode.class, RegistrationCardErrorCode.class, NicePayErrorCode.class})
@ApiErrorCodeExample({UserAuthErrorCode.class, OtherServerErrorCode.class, RegistrationCardErrorCode.class})
@Operation(summary = "04-02 Order💸 정기 결제용 카드 등록 api",description = "정기 결제를 위한 카드 등록 API 입니다.")
public CommonResponse<PortOneBillResponse> registrationCard(
@Parameter(hidden = true) @AuthenticationPrincipal User user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@
@ComponentScan(basePackages = {"com.example.matchbatch","com.example.matchdomain","com.example.matchinfrastructure", "com.example.matchcommon"})
@EnableScheduling
@EnableBatchProcessing
@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
@Slf4j
@SpringBootApplication@Slf4j
public class MatchBatchApplication{
public static void main(String[] args) {
SpringApplication.run(MatchBatchApplication.class, args);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ private Step regularPaymentStep() {
return stepBuilderFactory.get(JOB_NAME+"step")
.tasklet((contribution, chunkContext) -> {
log.info("Step!");
orderService.regularDonationPayment();
//orderService.regularDonationPayment();

return RepeatStatus.FINISHED;
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ public class PaymentScheduler {
@Scheduled(fixedDelay = 10000)
public void RegularPayScheduler(){
log.info("정기 결제 스케줄러가 시작");
discordFeignClient.alertMessage(discordConvertor.convertToAlertBatchMessage("정기 결제 스케줄러 시작",20));

Map<String, JobParameter> confMap = new HashMap<>();
confMap.put("time", new JobParameter(System.currentTimeMillis()));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
package com.example.matchcommon.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
Expand All @@ -12,6 +15,7 @@
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;
Expand Down Expand Up @@ -42,9 +46,16 @@ public EhCacheCacheManager ehcacheManager() {

@Bean(name = "redisCacheManager")
public CacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(objectMapper);


RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(serializer))
.disableCachingNullValues()
.entryTtl(Duration.ofHours(5L));

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ public RedisConnectionFactory redisConnectionFactory() {
.build())
.commandTimeout(Duration.ofSeconds(1000L)).build();

if(profile.equals("prod")){
if(profile.equals("prod")||profile.equals("dev")){
log.info(profile + " profile");
return new LettuceConnectionFactory(clusterConfiguration, clientConfiguration);
}else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ public class RedissonConfig {
public RedissonClient redissonClient() {
Config config = new Config();
log.info("RedissonConfig " + profile + " profile");
if (profile.equals("prod")) {
if (profile.equals("prod")||profile.equals("dev")) {
config.useClusterServers()
.addNodeAddress(REDISSON_HOST_PREFIX + redisProperties.getHost() + ":" + redisProperties.getPort())
// 다른 클러스터 노드도 필요에 따라 추가
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ public class QUserCard extends EntityPathBase<UserCard> {

public final StringPath cardPw = createString("cardPw");

public final StringPath code = createString("code");

//inherited
public final DateTimePath<java.time.LocalDateTime> createdAt = _super.createdAt;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ public Optional<User> existsSocialUser(String socialId, SocialType socialType){
return userRepository.findBySocialIdAndSocialType(socialId, socialType);
}

@Cacheable(value = "userCache", key = "#userId", cacheManager = "redisCacheManager")
public Optional<User> findByUserId(Long userId) {
System.out.println("캐싱 하자");
return userRepository.findById(userId);
Expand Down

0 comments on commit ab3c0b1

Please sign in to comment.