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.springfram

intellij lombok 인식 오류 error

이미지
  요즘 자바 개발에서 lombok 사용이 거의 필수가 되었습니다. intellij에서 롬복관련 자동완성이 안되고 컴파일 에러(실패)가 발생할 때가 있습니다.  (사용 버전은 2020.2.4 입니다. 설치가 된 버전도 있습니다.) 기본 예제 클래스 import lombok. Builder ; @Builder public class Book { private Integer id ; private String title ; } 컴파일 에러 @Test public void test () { Book book = Book. builder ().id( 1 ).title( " 제목 " ).build() ; // 코드 작성 } 테스트 코드를 실행시키면, 실행은 문제없이 됩니다. intellij에서 lombok가 인식되지 못 한 상태인데요. Window File > Settings ( Mac Intellij IDEA > Preferences) 메뉴에서 Plugins를 선택합니다. Lombok을 선택하여 설치(install)하고 재시작하면 완료됩니다. @Test public void test () { Book book = Book. builder ().id( 1 ).title( " 제목 " ).build() ; // 코드 작성 } 해결된 것을 볼 수 있습니다. 실행이 안될 때   혹시 실행이 안 되는 경우가 있습니다. 다음과 같이 해결 할 수 있습니다. Build > Compiler > Annotation Processors 메뉴에서 Enable annotation processing을 선택하면 완료 혹시 더 다른 문제나 방법이 있으면 문의 부탁드려요.

자바 Junit static 함수 Mocking

   지난번에 spring bean을 mocking 하는 코드는 작성했었는데, 이번에는 static함수를 응답을 mocking해보겠습니다. 1. 의존성 주입 testCompile group : 'junit' , name : 'junit' , version : '4.12' testImplementation 'org.mockito:mockito-inline:3.6.0' testImplementation 'org.mockito:mockito-core:3.6.0' testImplementation 'org.easytesting:fest-assert:1.4' static을 mocking하기 위해서는 mockito 3.4버전 이상부터 사용해야 합니다. mockito-inline가 추가되었습니다. (fest-assert는 필수아님) 2. static 함수 클래스 정의 public class AutoIncrement { private static int i = 0 ; public static int getId () { return i ++ ; } } getId를 하면 숫자를 순자적으로 반환하는 함수입니다. 특별한 의미는 없습니다. 3. 테스트 코드 작성 import com.hevia.example.AutoIncrement ; import org.junit. Test ; import org.mockito.MockedStatic ; import org.mockito.Mockito ; import static org.fest.assertions.Assertions.assertThat ; import static org.mockito.BDDMockito.given ; public class MockStaticTest { @Test public void mockStaticTest () { try (MockedStatic<AutoI

RestTemplate Config 설정 responseType Map 으로 응답 받기

  http 요청을 사용하여 외부의 자원을 호출하여 사용할 때가 많이 있습니다. 이와 관련된 기본 예제를 살펴 보겠습니다. Spring boot 프로젝트라고 가정하겠습니다. 라이브러리 추가 implementation 'org.apache.httpcomponents:httpclient:4.5.13' 기본 설정 추가 import org.springframework.context.annotation. Bean ; import org.springframework.context.annotation. Configuration ; import org.springframework.http.client. HttpComponentsClientHttpRequestFactory ; import org.springframework.web.client.RestTemplate ; @Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate () { HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory() ; requestFactory.setConnectTimeout( 1000 ) ; // 소켓 연결 타임아웃 requestFactory.setReadTimeout( 3000 ) ; // 소켓 연결 이후 응답 타임아웃 RestTemplate restTemplate = new RestTemplate(requestFactory) ; return restTemplate ; } } 클래스 객체 응답 받기 import lombok.extern.slf4j. Slf4j ; import org.springframework.b

nginx API Error JSON Response

이미지
  서버나 정적응답없이 nginx 즉시 오류를 응답하고 싶을 수 있습니다. 기본설정에는 root의 html 파일로 되어 있습니다. API의 웹서버로 사용하고 있는경우 Content-Type: application/json 의 json은 형식을 많이 사용합니다. 설정하기 nginx.conf server { listen 80 ; server_name localhost ; proxy_pass_header Server; location /api { if ($host = 'api.mylocalhost') { return 404; } proxy_pass http: //127.0.0.1:8080; } error_page 404 /404.json; location /404.json { return 404 '{"code": 404,"message": "Not Found"}'; } } 404.json에서 json으로 확장자를 하는 이유는 response header에 Content-Type: application/json 가 자동으로 세팅되게 됩니다. 호출하면 위와 같이 볼 수 있습니다. 그리고 if문 조건을 넣고 싶은경우 location 안에 추가해야합니다. if문 안에 location 을 추가하면 오류가 발생합니다. 이전 nginx 문서 설치 및 실행  https://withccm.blogspot.com/2020/12/macos-nginx.html Response Header Server 정보 제거 https://withccm.blogspot.com/2022/07/nginx-response-header-server.html

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.annotation.