라벨이 Spring인 게시물 표시

Spring Boot Admin Server, Client config 설정하기

이미지
 Spring Boot로 많은 프로젝트를 진행하게 됩니다. 많은 모니터링 도구가 있지만, Spring Boot 어플리케이션을 쉽게 모니터링 할 수 있는 방법을 소개하려고 합니다.   코드 중심으로 살펴보겠습니다. 1. 어드민 서버 구축 1-1. 디펜던시 추가 dependencies { // https://mvnrepository.com/artifact/de.codecentric/spring-boot-admin-starter-server implementation 'de.codecentric:spring-boot-admin-starter-server:2.5.4' } 1-2. 어드민 서버 설정 활성화 @SpringBootApplication @EnableAdminServer public class ServerApplication { public static void main (String[] args) { SpringApplication. run (ServerApplication. class, args) ; } } EnableAdminServer를 하면 됩니다. 2. 클라이언트 서버 설정  예제는 book-client, member-client 2가지 클라이언트, member-client가 2개의 인스턴스 실행으로 작성했습니다.  2-1 디펜던시 추가 dependencies { // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web implementation 'org.springframework.boot:spring-boot-starter-web:2.5.4' // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-actuator implementation 'org.spring...

Spring Boot Admin Server, Client config 설정하기

이미지
 Spring Boot로 많은 프로젝트를 진행하게 됩니다. 많은 모니터링 도구가 있지만, Spring Boot 어플리케이션을 쉽게 모니터링 할 수 있는 방법을 소개하려고 합니다.   코드 중심으로 살펴보겠습니다. 1. 어드민 서버 구축 1-1. 디펜던시 추가 dependencies { // https://mvnrepository.com/artifact/de.codecentric/spring-boot-admin-starter-server implementation 'de.codecentric:spring-boot-admin-starter-server:2.5.4' } 1-2. 어드민 서버 설정 활성화 @SpringBootApplication @EnableAdminServer public class ServerApplication { public static void main (String[] args) { SpringApplication. run (ServerApplication. class, args) ; } } EnableAdminServer를 하면 됩니다. 2. 클라이언트 서버 설정  예제는 book-client, member-client 2가지 클라이언트, member-client가 2개의 인스턴스 실행으로 작성했습니다.  2-1 디펜던시 추가 dependencies { // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web implementation 'org.springframework.boot:spring-boot-starter-web:2.5.4' // https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-actuator implementation 'org.spring...

Spring boot redis cache config

이미지
   안녕하세요. RedisTemplate 에 이어 redis cache를 알아보겠습니다.   전편 : Spring boot redis RedisTemplate에 대하여   전편에서 한 Redis 설정이 되어 있다고 가정하겠습니다. 1. 의존성 추가 implementation 'org.springframework.boot:spring-boot-starter-data-redis' 앞에서 의존성 추가를 이미 했으면 추가할 필요가 없습니다. 2. 캐시키 정의하기 import lombok. Getter ; import lombok. RequiredArgsConstructor ; import java.time.Duration ; @RequiredArgsConstructor @Getter public enum RedisCacheKey { BOOK (CacheNames. BOOK , Duration. ofMinutes ( 2 )) , STORE (CacheNames. STORE , Duration. ofHours ( 1 )) , ; private final String cacheName ; private final Duration expired ; public static class CacheNames { public static final String BOOK = "book" ; public static final String STORE = "store" ; } } Book과 Store 2가지 종류를 정의했습니다. 캐시키를 생성할 때 prefix로 사용될 cacheName과 만료시간(expired)를 선언했어요. 3. 캐시키 생성기 정의하기 import org.springframework.cache.interceptor.KeyGenerator ; import org.springframework.util.StringUtils ; import j...

Spring boot redis RedisTemplate

이미지
 안녕하세요. 스프링부트 프로젝트의 RedisTemplate 에 대해 알아 보겠습니다. Redis는 구동 되고 있다는 가정하에 작성하였습니다. 1. 의존성 추가 implementation 'org.springframework.boot:spring-boot-starter-data-redis' 2. RedisTemplate 설정 추가 2-1 yaml 파일에 설정 정의만 추가 스프링 부트에 yaml 파일에 정의만 해주면 자동으로 생성됩니다. spring : redis : host : localhost port : 6379 이외에도 옵션이 많은데 참고 사이트 링크로  대체하겠습니다. 위와 같이 설정이 추가된 상태이면 RedisTemplate 빈을 주입받을 수 있습니다, @Autowired private RedisTemplate redisTemplate ; 이 상태에서 레디스에 저장된 내용을 살펴보겠습니다. 제가 redisTemplate을 사용하여 key가 3으로 저장하였는데, 3으로 값을 조회하면 값이 나오지 않습니다. key를 조회해보면 이상한 문자값으로 저장된 것을 볼 수 있습니다.  해당 키로 조회하는경우 결과도 마찬가지 입니다. 이것은 redis에 저장할때 직렬화(serialize)/역직렬화시 JDK 방식으로 진행되기 때문입니다. 2-2 RedisConfig 설정 추가하기 앞의 문제를 해결하기 위해서 직접 설정 커스텀하여 추가할 수 있습니다. import lombok.extern.slf4j. Slf4j ; import org.springframework.beans.factory.annotation. Autowired ; import org.springframework.boot.autoconfigure.data.redis.RedisProperties ; import org.springframework.context.annotation. Bean ; import org.springframework.context....

Oauth jwt example

이미지
Oauth jwt API WEB 예제 샘플 코드 https://github.com/withccm/oauth-jwt-example API 서버와 WEB 클라이언트 oauth 로그인 인증 예제로 구성

Spring boot Webflux에서 block 찾기

이미지
Webflux로 개발하는 경우 block가 있으면 성능이 현저하게 낮아 집니다. 따라서 개발 후에 개발한 코드에 Block을 발생 시키는 코드가 있는지 확인하는 것은 중요합니다. 이것을 도와 주는 라이브러리가 Blockhound 입니다. 1. 의존성 추가 testImplementation( 'org.springframework.boot:spring-boot-starter-test' ) testImplementation 'io.projectreactor:reactor-test' testImplementation 'io.projectreactor.tools:blockhound:1.0.6.RELEASE' testImplementation 'io.projectreactor.tools:blockhound-junit-platform:1.0.6.RELEASE' Blockhound를 사용하면 Block을 발생시키는 곳에서 에러를 발생시킵니다. 따라서 운영 환경에서는 사용을 피해야 합니다. 테스트 환경에서 사용하는 것을 추천 드립니다. 2. 샘플 라우터 작성 @Configuration public class BlockingRouter { @Bean public RouterFunction<ServerResponse> blockRouter () { return RouterFunctions. route (RequestPredicates. GET ( "/nonBlock" ).and(RequestPredicates. accept (MediaType. APPLICATION_JSON )) , request -> { return ServerResponse. ok ().body(Mono. just ( "nonblock response" ) , String. class ) ; }).andRoute(RequestPredicates. GET ...

스프링 부트 프로파일 환경 설정 방법

이미지
Spring boot profile 환경 설정 방법 토이 프로젝트가 아닌 사용자에게 서비스할 프로젝트인 경우 개발 환경과 서비스 환경을 분리해서 구성해야할 필요가 있습니다. 스프링 부트 프로젝트 생성 https://start.spring.io/ 스프링 부트 프로젝트를 쉽게 세팅할 수 있다. 간단히 웹 디펜던시만 추가하였습니다. (세팅하는데 없어도 상관없습니다.) 파일을 분리하는 방법과 하나의 파일에 환경별로 작성하는 방법이 있습니다. 1. 파일을 분리하는 방법 파일 생성 및 구성 위의 이미지처럼 환경별로 파일을 생성합니다. application-{환경}.properties 예시는 로컬, 개발, 실서비스 3가지로 작성되었습니다. #application-local.properties logging.level.org.springframework = DEBUG #application-dev.properties logging.level.org.springframework = INFO #application-prod.properties logging.level.org.springframework = WARN 실행할 때 환경을 세팅하는 방법 1. 설정 파일에 정의하기 #application.properties spring.profiles.active = local 2. 실행할 때 주입하기 Active profiles: 원하는 환경 3. mvn 빌드시 설정 mvn -Dspring.profiles.active=prod spring-boot:run & 2. 하나의 파일에 환경별로 작성하는 방법 #application.yml --- spring : profiles : local, dev logging : level : org.springframework : DEBUG --- spring : profiles : test logging : level : org.springframework : INFO --- spring : profiles : ...

자바 스프링 설정값 사용하기

이미지
자바에서 스프링 설정 읽는 두가지 방법을 설명하겠습니다. 자바 설정을 통하여 읽어 올 수 있습니다. @Configuration @PropertySource ( "classpath:filename.properties" ) 파일에 include를 정의하여 읽어 올 수 있습니다. 스프링부트에서 기본적으로 applicaion.*를 설정 파일을 읽어오도록 되어 있습니다. 스프링부트 > 설정 파일 예시 *.yml 파일에서 읽을 파일 목록 정의하기 spring : profiles : include : - env - datasource - redis application-env.yml 파일에 설정 정의 env : api : host : localhost.withccm 정의된 설정값 사용하기 import org.springframework.beans.factory.annotation. Autowired ; import org.springframework.beans.factory.annotation. Value ; import org.springframework.context.annotation. Configuration ; import org.springframework.core.env.Environment ; @Value ( "${env.api.host}" ) private String apiHost ; @Autowired private Environment env ; public String getApiHost () { return env .getProperty( "env.api.host" ) ; } @Value 어노테이션을 통하여 정의된 사용할 값을 할당하여 사용합니다. 읽어야할 설정이 많은 경우 일일히 정의해야 하기 때문에 선언 부분이 길어질 수 있습니다. 또는 스프링 환경인 Environment 를 주입 받아, getProperty 함수를 호출하여 사...