네로개발일기

개발자 네로의 개발 일기, 자바를 좋아합니다 !

'2022/03'에 해당되는 글 23건


반응형

서버의 상태를 확인하려면 Health Check를 사용하면 된다.

implementation('org.springframework.boot:spring-boot-starter-actuator')

- Health Check 기능은 spring-boot-starter-actuator 라이브러리의 기능 중 하나이므로 사용하려면 actuator 라이브러리를 추가해야 한다.

- spring-boot-starter-actuator 라이브러리는 Spring Boot 버전과 동일한 버전을 사용해야 한다.

management:
  endpoints:
    web:
      base-path: /application
      path-mapping:
        health: healthcheck
  endpoint:
    health:
      show-details: always

base-path: actuator의 base path를 설정한다. (기본값은 /actuator)

path-mapping.health: health-check end point (기본값은 health)

show-details: health check API를 접근할 때 세부 정보를 확인한다. (never, when-authorized, always/ 기본값은 never)

 

# show-details: never로 설정
{"status": "UP"}

# show-details: always로 설정
{"status": "UP", 
 "details": {
   "diskSpace": {
     "status: "UP", 
     "details": {
       "total": 234685313024,
       "free": 158591512576,
       "threshold": 10485760
     }
   },
   "redis": { 
     "status":"UP",
     "details":{"version":"5.0.7"}
   },
   "db":{
     "status":"UP",
     "details":{
       "database":"MariaDB",
       "hello":1
     }
   }
 }
}
728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

 

1. Spring JPA query IN clause example

@Repository
@Transactional
public interface EmployeeDAO extends JpaERepository<Employee, Integer> {
    // 1. Spring JPA In Cause using method name
    List<Employee> findByEmployeeNameIn(List<String> names);
   
    // 2. Spring JPA In cause using @Query
    @Query("SELECT e FROM Employee e WHERE e.employeeName IN (:names)")
    List<Employee> findByEmployeeNames(@Param("names") List<String> names);
    
    // 3. Spring JPA In cause using native query
    @Query(nativeQuery = true, value = "SELECT * FROM Employee as e WHERE e.employeeName IN (:names)")
    List<Employee> findByEmployeeName(@Param("names") List<String> names);
}

 

2. Spring JPA query NOT IN clause example

@Repository
@Transactional
public interface EmployeeDAO extends JpaRepository<Employee, Integer> {
    
    // 1. Spring JPA In cause using method name
    List<Employee> findByEmployeeNameNotIn(List<String> names);
    
    // 2. Spring JPA In cause using @Query
    @Query("SELECT e FROM Employee e WHERE e.employeeName NOT IN (:names)")
    List<Employee> findByEmployeeNamesNot(@Param("names") List<String> names);
    
    // 3. Spring JPA In cause using native query
    @Query(nativeQuery = true, value = "SELECT * FROM Employee as e WHERE e.employeeName NOT IN (:names)")
    List<Employee> findByEmployeeNameNot(@Param("names") List<String> names);
}

 

3. Spring JPA dynamic IN Query

public List<Employee> findByInCriteria(List<String> names) {
    return employeeDAO.findAll(new Specification<Employee>() {
        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
            List<Predicate> predicates = new ArrayList<>();
            
            if (names != null && !names.isEmpty()) {
                predicates.dd(root.get("employeeName").in(names));
            }
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        });
    }
}

 

4. Spring JPA dynamic NOT IN Query

public List<Employee> findByInCriteria(List<String> names) {
    return employeeDAO.findAll(new Specification<Employee>() {
        @Override
        public Predicate toPredicate(Root<Employee> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
            List<Predicate> predicates = new ArrayList<>();
            
            if (names != null && @!names.isEmpty()) {
                predicates.add(criteriaBuilder.not(root.get("employeeName").in(names)));
            }
            
            return criteriaBuilder.and(predicates.toArray(new Predicate[predicates.size()]));
        }
    });
}

 

 

https://javadeveloperzone.com/spring/spring-jpa-query-in-clause-example/

 

Spring JPA query IN clause example - Java Developer Zone

Here is article of Spring JPA query IN clause example and Spring data JPA IN and NOT IN query with example, dyanic IN and NOT IN query with spring JPA.

javadeveloperzone.com

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

Spring Boot에서는 default context path를 / 로 설정한다. 대부분의 웹서버, WAS, 혹은 Spring boot의 내장 서버 역시 다 root 를 기본으로 가지고 있다. 즉, 로컬 개발시, http://localhost:8080/ 과 같은 주소가 되는 것이다. 그리고 각 controller에서 설정한 Request Mapping 정보에 따라서 그 하위 경로가 생성된다.

그런데 경우에 수정해야 하는 경우가 있다. 물론 그에 따른 loadbalancing이나 gateway 역할은 다른 서버가 할 수도 있지만, 하나의 프로그램 단위별로 최상의 경로를 다르게 명명하는 경우도 있다. 이것 역시 설정 파일인 application.yml에 설정하게 된다.

 

Property 조정으로 설정

application.properties 파일을 수정하여 적용하는 것이 가장 효율적인 적용 방법이다. 다른 여러가지 방법이 있고, Spring의 기본 개게를 상속(구현)하여 적용하는 방법 역시 가능하다. 하지만 Spring Boot는 application.properties 파일을 통한 설정 변경을 권장하고 있고, 더욱 상세한 설정이나 properties 파일로 적용되지 않는 사항을 제외하고는 가급적이면 properties 파일을 수정하여 적용하는 것을 권장한다.

다른 설정들처럼, SpringBoot에서는 property 파일을 통해 이를 설정할 수 있다. server.servlet.context-path 이다.

 


* application.properties / yml 파일 수정하여 적용하기

server.servlet.context-path=/jiyoon

스프링 프로젝트를 재실행하면 http://localhost:8080/jiyoon 를 통해서만 접속되는 것을 확인할 수 있다.

 

* Java System Property 이용하기

Java System Property(환경변수)를 이용할 수도 있다. 이 방식을 사용하여면 context가 초기화되기 전에 넣어준다. 

생성한 프로젝트의 시작 class 가 되는 {프로젝트명}Application.java 파일을 열어 main() 함수를 찾습니다. 이 곳이 프로젝트 구동의 시작점이 되는 곳이므로 아래와 같은 내용을 추가해주면 된다. 환경변수를 설정하는 것인데, java -jar 명령어와 함께 환경변수를 넣어주는 것과 동일한 효과를 갖습니다.

public static voin main(String[] args) {
    System.setProperty("server.servlet.context-path", "/jiyoon");
    SpringApplication.run(Application.class, args);
}

위 예제에서 SpringApplication.run() 부분이 실제 서버가 구동되기 시작하는 부분이므로 그보다 앞에 작성해야 한다.

 

* OS 환경 변수 이용

Spring Boot는 시스템의 환경변수를 사용할 수 있다. 이는 앞서 설명한 System.setProperty()에서 설정하는 것과 동일한 효과를 갖는다. 원하는 형태로 변경해서 진행해도 되지만, 하나의 시스템에 여러 개의 어플리케이션을 구동하는 경우에는 정상적으로 구동되지 않을 수 있다. 

Unix 기반 시스템에서는 다음을 입력해 환경 변수를 설정해준다. 이 명령을 입력한 창을 닫지 않고 세션을 그대로 둔 채로 프로그램을 구동해야 한다.

$ export SERVER_SERVLET_CONTEXT_PATH=/jiyoon

윈도우 환경이면 아래처럼 입력한다.

> set SERVER_SERVLET_CONTEXT_PATH=/jiyoon

 

* Command line에서 설정하기

Spring Boot를 실행하는 명령어 상에서 argument로 설정할 수 있다. 실제 운영에서 이렇게 사용하기보다는 특정 상황에 따라 가변적으로 적용해야 하는 경우에만 임시로 사용하기를 권장한다.

$ java -jar app.jar --server.servlet.context-path=/jiyoon

 

Java Config 이용하기

Bean Factory를 Configuration Bean과 함께 생성하는 방법으로 context path를 설정할 수 있다. 실제로 앞서 설명한 환경 변수, 혹은 설정파일을 이용한 방법이 내부적으로 Configuration을 통해서 로드한다.

Configuration을 이용하는 것은 이미 설정 파일이나 환경 변수로 로드된 것을 다시 설정하는 것이다.

 

Spring boot 2.X 버전에서는 아래와 같이 설정한다.

@Bean
public WebServerFactoryCustomizer<ConfigurationServletWebServerFactory> webServerFactoryCustomizer() {
    return factory -> factory.setContextPath("/jiyoon");
}

Spring boot 1.X 버전에서는 아래와 같이 설정한다.

@Bean
public EmbededServletContainerCustomizer embededServletContainerCustomizer() {
    return container -> container.setContextPath("/jiyoon");
}

 

설정한 내용들의 우선순위

1. Java Config

2. Command Line Arguments

3. Java System Properties

4. OS Environment Variables

5. application.properties in Current Directory

6. application.properties in the classpath(src/main/resources or the packaged jar file)

 

 

 출처 

https://linkeverything.github.io/springboot/spring-context-path/

 

Spring Boot 에서 Context Path 설정하기

Springboot 에서는 default context path 를 / 로 설정합니다. 대부분의 웹서버, WAS, 혹은 Springboot 의 내장 서버 역시 다 root 를 기본으로 가지고 있습니다. 즉, 로컬 개발 시 http://localhost:8080/ 과 같은 주소

linkeverything.github.io

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

scp 명령어

ssh 원격 접속 프로토콜을 기반으로 Secure Copy의 약자로 원격지에 있는 파일과 디렉터리를 보내거나 가져올 때 사용하는 파일 전송 프로토콜이다. 네트워크가 연결되어 있는 환경에서 ssh와 동일한 22번 포트와 identity file을 사용해서 파일을 송수신하기 때문에 보안적으로 안정된 프로토콜이다.

Local 로컬에서 Remote 원격지

1. 단일 파일을 원격지로 보낼 때

# scp [옵션] [파일명] [원격지_id]@[원격지_ip]:[파일이 저장될 경로]
# scp testfile2 root@192.168.12.14:/tmp/testclient

 

2. 복수의 파일을 원격지로 보낼 때

# scp [옵션] [파일명1] [파일명2] [원격지_id]@[원격지_ip]:[파일이 저장될 경로]
# scp testfile1 testfile2 root@192.168.12.52:/tmp/testclient

 

3. 여러 파일을 포함하고 있는 디렉터리를 원격지로 보낼 때 (-r 옵션을 사용한다)

# scp [옵션] [디렉터리 이름] [원격지_id]@[원격지_ip]:[파일이 저장될 경로]
# scp -r testdirectory root@192.168.12.52:/tmp/testclient

 

r 디렉터리 내 모든 파일/디렉터리 복사 scp -r
p (소문자) 원본 권한 속성 유지 복사 scp -p
P (대문자) 포트 번호 지정 복사 scp -P [포트번호] 
c (소문자) 압축 복사 scp -c 
v 과정 출력 복사 scp -v
a 아카이브 모드 복사 scp -a

 

Remote 원격지에서 Local 로컬

1. 단일 파일을 원격지에서 로컬로 가져올 때

# scp [옵션] [원격지_id]@[원격지_ip]:[원본 위치] [로컬 서버에 저장될 경로]
# scp root@192.168.14.12:/tmp/testclient/testfile1 /tmp

 

2. 복수의 파일을 원격지에서 로컬로 가져올 때

# scp [옵션] [원격지_id]@[원격지_ip]:[원본 위치1] [원본 위치2] [로컬 서버에 저장될 경로]
# scp root@192.168.14.12:"/tmp/testclient/testfile1 /tmp/testclient/testfile2" /tmp

 

3. 여러 개의 파일을 포함하는 디렉터리 원격지에서 로컬로 가져올 때

# scp [옵션] [원격지_id]@[원격지_ip]:[디렉터리 위치] [로컬 서버에 저장될 경로]
# scp -r root@192.168.14.12:/tmp/testclient/test /tmp
728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !

반응형

 

[ 이전 글 ] Apache POI를 이용한 엑셀 파일 읽기

https://frogand.tistory.com/126

 

[Spring] Apache POI 를 이용한 엑셀 파일 읽기

[Spring] Apache POI 를 이용한 엑셀 파일 읽기 ✨ 의존성 - Spring Boot - Spring Web - Thymeleaf - Lombok 1. Apache POI , Tika 관련 의존성 추가 maven일 경우 pom.xml org.apache.poi poi 4.1.2 org...

frogand.tistory.com

 

 문제 상황 

POI 라이브러리를 사용해서 Excel 작업을 진행 중이었다.

근데 Excel 용량이 커서인지 진행이 되지 않았음. 계속 뜨는 오류 메시지는 

java.lang.OutOfMemoryError: Java heap space

[삽질 1] Exceed Java Heap Size 

Xmx를 늘려주었다.. 4096M 까지.. (사실 얼마나 늘려야할지 몰랐는데, 아무튼 이게 문제가 아니라는 것을 깨달음)

- 참고: Xmx 옵션은 자바 힙 사이즈의 최대를 결정해주는 옵션이다. 

- 참고: 엑셀 파일의 크기는 58M에서 87M였다.

 

그래도 되지 않았다.

 

[삽질 2] Thread Starvation

HikariPool-1 - Thread starvation or clock leap detected

thread 사용하지도 않았는데 갑자기 Thread starvation,, => Multi-Threaded JDBCTemplate 사용해봤지만

역시나 되지 않았다.

 

[삽질 3] SXSSFWorkbook

=> XSSFWorkbook를 생성하는 시점부터 문제가 생기는 것을 알고,  XSSFWorkbook에 문제가 있을 것 같다는 생각과 함께...

Workbook workbook = new XSSFWorkbook(file.getInputStream());

SXSSFWorkbook 방식이 있다는 것을 알았지만, Write Only로 엑셀 파일을 만들 때만 사용할 수 있다. 

엑셀 파일 읽기에는 사용이 불가능했다.

 

 

 해결 방안 

=> SAX를 이용하여 Excel 파일 읽기

* pom.xml에 의존성을 추가

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId> <!-- 엑셀 2007 이상 버전에서 사용 -->
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>sax</groupId>
    <artifactId>sax</artifactId>
    <version>2.0.1</version>
</dependency>

ExcelSheetHandler.java

import org.apache.poi.ooxml.util.SAXHelper;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.eventusermodel.ReadOnlySharedStringsTable;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.eventusermodel.XSSFSheetXMLHandler;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.XSSFComment;
import org.xml.sax.ContentHandler;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;

import java.io.File;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ExcelSheetHandler implements XSSFSheetXMLHandler.SheetContentsHandler {

    private int currentCol = -1;
    private int currRowNum = 0;

    private List<List<String>> rows = new ArrayList<List<String>>();    //실제 엑셀을 파싱해서 담아지는 데이터
    private List<String> row = new ArrayList<String>();
    private List<String> header = new ArrayList<String>();

    public static ExcelSheetHandler readExcel(File file) throws Exception {

        ExcelSheetHandler sheetHandler = new ExcelSheetHandler();
        try {

            OPCPackage opc = OPCPackage.open(file);
            XSSFReader xssfReader = new XSSFReader(opc);
            StylesTable styles = xssfReader.getStylesTable();
            ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(opc);

            //엑셀의 시트를 하나만 가져오기.
            //여러개일경우 iter문으로 추출해야 함. (iter문으로)
            InputStream inputStream = xssfReader.getSheetsData().next();
            InputSource inputSource = new InputSource(inputStream);
            ContentHandler handle = new XSSFSheetXMLHandler(styles, strings, sheetHandler, false);

            XMLReader xmlReader = SAXHelper.newXMLReader();
            xmlReader.setContentHandler(handle);
            
            xmlReader.parse(inputSource);
            inputStream.close();
            opc.close();
        } catch (Exception e) {
            //에러 발생했을때
        }

        return sheetHandler;

    }

    public List<List<String>> getRows() {
        return rows;
    }

    @Override
    public void startRow(int arg0) {
        this.currentCol = -1;
        this.currRowNum = arg0;
    }

    @Override
    public void cell(String columnName, String value, XSSFComment var3) {
        int iCol = (new CellReference(columnName)).getCol();
        int emptyCol = iCol - currentCol - 1;

        for (int i = 0; i < emptyCol; i++) {
            row.add("");
        }
        currentCol = iCol;
        row.add(value);
    }

    @Override
    public void headerFooter(String arg0, boolean arg1, String arg2) {
        //사용 X
    }

    @Override
    public void endRow(int rowNum) {
        if (rowNum == 0) {
            header = new ArrayList(row);
        } else {
            if (row.size() < header.size()) {
                for (int i = row.size(); i < header.size(); i++) {
                    row.add("");
                }
            }
            rows.add(new ArrayList(row));
        }
        row.clear();
    }

    public void hyperlinkCell(String arg0, String arg1, String arg2, String arg3, XSSFComment arg4) {
        // TODO Auto-generated method stub

    }
}

 

아래는 위 ExcelSheetHandler를 사용하는 방법이다.

// 엑셀 데이터 양식 example
/*    A열				B열
1행   nero@nate.com		Seoul
2행   jijeon@gmail.com	Busan
3행   jy.jeon@naver.com	Jeju
*/

String filePath = "/Users/jyjeon/Downloads/정의서/복사본.xlsx";
File file = new File(filePath);

ExcelSheetHandler excelSheetHandler = ExcelSheetHandler.readExcel(file);

// excelDatas >>> [[nero@nate.com, Seoul], [jijeon@gmail.com, Busan], [jy.jeon@naver.com, Jeju]]
List<List<String>> excelDatas = excelSheetHandler.getRows();

for(List<String> dataRow : excelDatas) // row 하나를 읽어온다.
    for(String str : dataRow){ // cell 하나를 읽어온다.
        System.out.println(str);
    }
}

 

 

출처

https://poi.apache.org/components/spreadsheet/how-to.html#xssf_sax_api

 

The New Halloween Document

<!--+ |breadtrail +--> <!--+ |start Menu, mainarea +--> <!--+ |start Menu +--> <!--+ |end Menu +--> <!--+ |start content +--> The New Halloween Document How to use the HSSF API Capabilities This release of the how-to outlines functionality for the current

poi.apache.org

https://m.blog.naver.com/hyoun1202/220245067954

 

[JAVA] Apache POI를 사용한 Excel 파일 읽기(대용량 Excel 파일 읽기 포함)

Apache POI를 사용해서 Excel 파일을 읽어들이는 방법에는 4가지 방법이 있다. 1번째 방법 - FileIn...

blog.naver.com

https://hoonzi-text.tistory.com/29

 

java excel read 문제 해결 (XSSFWorkbook heap space OOM)

이전 포스트 했던 excel 관련해 발생한 문제가 있어 정리 해보려고 한다. java excel 처리 정리 java excel 처리 정리 매번 엑셀을 java로 읽을때마다 찾아보는게 귀찮아서 정리한다. 사용 모듈 apache poi

hoonzi-text.tistory.com

 

728x90
반응형
blog image

Written by ner.o

개발자 네로의 개발 일기, 자바를 좋아합니다 !