반응형

runDev.bat

set JAVA_HOME=%CD%\java\zulu-11
set path=%JAVA_HOME%\bin;%PATH%;
set classpath=.

cd sts-4.13.0.RELEASE

SpringToolSuite4.exe
반응형

'java, spring' 카테고리의 다른 글

400Bad Request: 필수파라미터 누락 등의 에러, 삽질방지위해서는 에러메세지 잘보자!  (0) 2024.01.19
java stream  (0) 2022.04.28
Quartz  (0) 2022.04.19
Tomcat's directories  (0) 2021.03.03
Java Web Application  (0) 2021.03.02
반응형

SecurtyContext이런용어 때문에 보안토큰에 문제있을거라고 생각했으나 아니었음, 밑에 Exception message를 잘봐야했음

2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.security.web.FilterChainProxy - Securing POST /files/manual/upload/00060101_PlantInfo/2024/01/
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.c.SecurityContextPersistenceFilter - Set SecurityContextHolder to empty SecurityContext
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.a.AnonymousAuthenticationFilter - Set SecurityContextHolder to anonymous SecurityContext
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.a.i.FilterSecurityInterceptor - Authorized public object filter invocation [POST /files/manual/upload/00060101_PlantInfo/2024/01/]
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.security.web.FilterChainProxy - Secured POST /files/manual/upload/00060101_PlantInfo/2024/01/
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.c.HttpSessionSecurityContextRepository - Did not store anonymous SecurityContext
2024-01-19 10:29:24 [http-nio-8007-exec-10] [WARN ] o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'UploadFiles' is not present]
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.c.HttpSessionSecurityContextRepository - Did not store anonymous SecurityContext
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.c.SecurityContextPersistenceFilter - Cleared SecurityContextHolder to complete request
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.security.web.FilterChainProxy - Securing POST /error
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.c.SecurityContextPersistenceFilter - Set SecurityContextHolder to empty SecurityContext
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.a.AnonymousAuthenticationFilter - Set SecurityContextHolder to anonymous SecurityContext
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.security.web.FilterChainProxy - Secured POST /error
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.c.HttpSessionSecurityContextRepository - Did not store anonymous SecurityContext
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.c.HttpSessionSecurityContextRepository - Did not store anonymous SecurityContext
2024-01-19 10:29:24 [http-nio-8007-exec-10] [DEBUG] o.s.s.w.c.SecurityContextPersistenceFilter - Cleared SecurityContextHolder to complete request
2024-01-19 10:29:26 [pool-2-thread-1] [DEBUG] o.a.h.i.c.PoolingHttpClientConnectionManager - Closing expired connections
2024-01-19 10:29:26 [pool-2-thread-1] [DEBUG] o.a.h.i.c.PoolingHttpClientConnectionManager - Closing connections idle longer than 30 SECONDS

반응형

'java, spring' 카테고리의 다른 글

[windows] sts(SpringToolSuite) eclipse 실행 script  (0) 2024.01.25
java stream  (0) 2022.04.28
Quartz  (0) 2022.04.19
Tomcat's directories  (0) 2021.03.03
Java Web Application  (0) 2021.03.02
반응형

Group by

public List<RegionPayload> getAllRegions() {
  List<RegionPayload> result = new ArrayList<>();
  List<Region> allRegion = regionRepository.findAll();
  Map<String, List<Region>> regionMap =
      allRegion.stream().collect(Collectors.groupingBy(Region::getRegion));
  for (Map.Entry<String, List<Region>> elem : regionMap.entrySet())
    result.add(new RegionPayload(elem.getKey(), elem.getValue()));
  return result;
}
import com.lge.cdp.model.Region;
import java.util.List;
import lombok.AllArgsConstructor;
// import lombok.ToString;
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@AllArgsConstructor
// @ToString
public class RegionPayload {

  private String region;
  private List<Region> countryList;
}
반응형
반응형
  • 장점
    • DB기반으로 스케쥴러간 clustering 기능제공 -> ???
    • system fail-over와 random방식 로드분산처리 지원 -> ???
    • in-memory job scheduler 제공
    • 여러 기본 plugin 제공
    • shutdownHookPlugin - JVM 종료 이벤트를 캐치해서 스케줄러에게 종료를 알려줌
    • LoggingJobHistoryPlugin - job실행에 대한 로그를 남겨 디버깅할 때 유용함
  • 단점
    • clustering을 제공하지만 단순한 랜덤방식이라서 완벽한 cluster간의 로드 분산은 안됨
    • 어드민 UI제공안됨
    • 스케쥴링 실행에 대한 history보관안함
    • fixed delay 타입 보장하지 않으므로 추가작업 필요
  • how to manually trigger job
    • update qrtz_triggers set next_fire_time = 0 (이전보다 작은 시간으로 바꾸면 자동실행됨)
  • job삭제시 주의사항
    •  삭제하려는 job정보를 DB quartz 테이블에서 삭제하지 않고 소스만 삭제하고 돌리면 에러발생
      • qrtz_cron_triggers삭제후 -> qrtz_trigger삭제해야함
      • qrtz_job_details 삭제안해도 에러는 안났음
      • Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'schedulerFactoryBean'; nested exception is org.springframework.scheduling.SchedulingException: Could not start Quartz Scheduler; nested exception is org.quartz.SchedulerConfigException: Failure occured during job recovery. [See nested exception: org.quartz.JobPersistenceException: Couldn't store trigger 'DEFAULT.Sync_ibs_channel_map_data_batch_trigger' for 'DEFAULT.BATCH_IBS_CHANNEL_MAP_SYNC' job:Couldn't retrieve job because a required class was not found: com.lge.cdp.batch.CollectIbsChMapJob [See nested exception: org.quartz.JobPersistenceException: Couldn't retrieve job because a required class was not found: com.lge.cdp.batch.CollectIbsChMapJob [See nested exception: java.lang.ClassNotFoundException:
반응형

'java, spring' 카테고리의 다른 글

400Bad Request: 필수파라미터 누락 등의 에러, 삽질방지위해서는 에러메세지 잘보자!  (0) 2024.01.19
java stream  (0) 2022.04.28
Tomcat's directories  (0) 2021.03.03
Java Web Application  (0) 2021.03.02
tomcat  (0) 2021.03.02
반응형
  • bin: contains the binaries; and startup script (startup.bat for Windows and startup.sh for Unixes and Mac OS), shutdown script (shutdown.bat for Windows and shutdown.sh for Unix and Mac OS), and other binaries and scripts.

    -   catalina.sh - 여기에 변수 추가는 안해야함 (하지말라고 나와있음 Do not set the variables...)
    -   setenv.sh, setenv.bat 여기에다 java option, classpath 추가할 것
  • conf: contains the system-wide configuration files, such as server.xml, web.xml, and context.xml.

    • server.xml

      • main 설정파일, startup 초기 설정 담당
      • port, document root path (localhost:80 고양이 그림)
        <Server port="${port.shutdown}" shutdown="SHUTDOWN">
        <Connector port="${port.http}" protocol="HTTP/1.1"
           maxParameterCount="-1" maxPostSize="-1" maxThreads="512" connectionTimeout="90000"
           redirectPort="${port.https}" URIEncoding="UTF-8"/>
        <Connector executor="tomcatThreadPool"
           port="8080" protocol="HTTP/1.1"
           connectionTimeout="90000"
           redirectPort="8443" />
        <Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150" SSLEnabled="true">
        <SSLHostConfig>
            <Certificate certificateKeystoreFile="conf/localhost-rsa.jks"
                     type="RSA" />
        </SSLHostConfig>
        </Connector>
        <Connector port="8443" protocol="org.apache.coyote.http11.Http11AprProtocol"
           maxThreads="150" SSLEnabled="true" >
        <UpgradeProtocol className="org.apache.coyote.http2.Http2Protocol" />
            <SSLHostConfig>
                <Certificate certificateKeyFile="conf/localhost-rsa-key.pem"
                     certificateFile="conf/localhost-rsa-cert.pem"
                     certificateChainFile="conf/localhost-rsa-chain.pem"
                     type="RSA" />
            </SSLHostConfig>
        </Connector>
        <Connector port="${port.ajp}" protocol="AJP/1.3" redirectPort="${port.https}"
            maxParameterCount="-1" maxPostSize="-1" maxThreads="512" connectionTimeout="90000" URIEncoding="UTF-8"/>
        
        --> -Dport.http=8180 -Dport.https=8543 -Dport.ajp=8109 -Dport.shutdown=8105
            nc -z 10.150.33.35 8180으로 확인결과 8180 8109 8080-open, 8543,8443-close
            browser에서는 8180만 응답됨, 8080은 Whitelabel Error Page(권한없는 화면접속시 발생)
        --> port="${port.http}" connectionTimeout="90000" 20000으로 고쳐도 1분후 응답받음 why?
  • web.xml

    • 톰캣의 실행환경에 대한 정보를 담당하는 '환경설정' 파일 이다.
    • 각종 servlet의 설정과 servlet 매핑, 필터, 인코딩 등을 담당한다.
    • web.xml은 톰캣에 있는 모든 web application의 기본설정을 정의한다.
    • web.xml은 각 application이 deploy될 때 각 application의 'WEB-INF/web.xml' deployment descripter에 따라서 처리가 된다.
    • 각 application 마다 설정시, web.xml은 파일을 복사해서 필요한 것만 적으면 그게 기본 것을 override해서 적용된다.
    • 30: 분단위, 30분이라는 의미, default sesseion timeout 30분
    • 역시 되도록 수정하지 말고, 각 application별로 필요한 것은 따로 지정해서 사용하자
  • context.xml

    • 원래 server.xml에 있었으나 자주 변경되는 를 context.xml로 따로 빼서 사용함 (tomcat ver5.5.12부터)
  • webapps: contains the webapps to be deployed. You can also place the WAR (Webapp Archive) file for deployment here.

  • lib: contains the Tomcat's system-wide JAR files, accessible by all webapps. You could also place external JAR file (such as MySQL JDBC Driver) here.

  • work: Tomcat's working directory used by JSP, for JSP-to-Servlet conversion

  • logs: contains Tomcat's log files. You may need to check for error messages here

  •  
    설정위치
  • manager.yyyy-mm-dd.log
  • host-manager.yyyy-mm-dd.log
특정 managing을 담당하는 application에 의해 남는 로그 (in conf/logging.properties)
  • localhost_access_log.yyyy-mm-dd.txt 
어떤 접근에 대한 log

(in conf/server.xml) prefix="localhost_access.log." suffix=".txt"

  • localhost.yyyy-mm-dd.log
내부적으로 관리하는 host에 대한 내용 (in conf/logging.properties)
  • catalina.out

전반적인 console 로그

(각 application에서 발생하는 system out console)

(in bin/catalina.sh) CATALINA_OUT="$CATALINA_BASE"/logs/catalina.out → 경로 바꾸고 싶으면 setenv.sh, setenv.bat에 CATALINA_OUT 변수와 값을 추가하자!

  • catalina.yyyy-mm-dd.log
catalina engine에 대한 내용 (in conf/logging.properties)
반응형

'java, spring' 카테고리의 다른 글

java stream  (0) 2022.04.28
Quartz  (0) 2022.04.19
Java Web Application  (0) 2021.03.02
tomcat  (0) 2021.03.02
spring-boot profile별 실행  (0) 2020.03.25
반응형

Java Web Application

           

  1. Web Server and Client
  2. HTML and HTTP
  3. Understanding URL
  4. Why we need Servlet and JSPs?
    Web servers are good for static contents HTML pages but they don’t know how to generate dynamic content or how to save data into databases
    Servlet/JSP: server side technologies to extend the capability of web servers
    ASP, PHP, CGI...

  5. Web Container
    1. Communication Support – provides easy way of communication between web server and the servlets and JSPs. We don’t need to build a server socket to listen for any request from web server, parse the request and generate response.
    2. Lifecycle and Resource Management – takes care of managing the life cycle of servlet. (loading the servlets into memory, initializing servlets, invoking servlet methods and destroying them)
    3. Multithreading Support – creates new thread for every request to the servlet and when it’s processed the thread dies. So servlets are not initialized for each request and saves time and memory.
    4. JSP Support – Every JSP is compiled by container and converted to Servlet.
    5. Miscellaneous Task – manages the resource pool, does memory optimizations, run garbage collector, provides security configurations, support for multiple applications, hot deployment and several other tasks.
  6. Web Application Directory Structure (Java Servlet API requirements)

    WEB-INF  is a private directory, but  accessible to the resource loader of Web-Application.
    META-INF is related to .jar files, contains the manifest (main class, security policy, component info, sealing info...) of a jar and is created when you write a jar file. 
  7. Deployment Descriptor web.xml file 
    mapping for servlets-URL (prior to 3.0), welcome/error pages, security configurations, listener, filter, session timeout settings etc.

 

Servlet (https://www.journaldev.com/1877/servlet-tutorial-java)

JEE server driven technology (javax.servlet, javax.servlet.http)

  • better performance-multithreading
  • platform independent
  • robust because container takes care of life cycle of servlet and we don’t need to worry about memory leaks, security, garbage collection etc.
  • maintainable and learning curve is small

 

  • ① 사용자가 URL을 클릭하면 HTTP Request를 Servlet Container에 보낸다.
  • ② Servlet Container는 HttpServletRequest, HttpServletResponse 두 객체를 생성한다.
  • ③ 사용자가 요청한 URL을 분석하여 어느 서블릿에 대한 요청인지 찾는다. (DD를 참조하여 분석)
  • ④ 컨테이너는 서블릿 service() 메소드를 호출하며, POST, GET여부에 따라 doGet() 또는 doPost()가 호출된다.
  • ⑤ doGet() or doPost() 메소드는 동적인 페이지를 생성한 후 HttpServletResponse객체에 응답을 보낸다.
  • ⑥ 응답이 완료되면 HttpServletRequest, HttpServletResponse 두 객체를 소멸시킨다.

 

    • Servlet Interface
    • ServletConfig Interface
    •  

ServletContext interface

    •  

    •  

ServletRequest interface

    •  

    •  

ServletResponse interface

    •  

    •  

RequestDispatcher interface

    •  

    •  

GenericServlet class

    •  

    •  

HTTPServlet class

  •  

inter-servlet communication

  • RequestDispatcher.forward: request를 다른 servlet으로 보내는데 container에서 내부적으로 처리됨
    • The path must begin with a / and is interpreted as relative to the current context root. (/로 시작해야하는 제약....이런건 왜......)
  • Response.sendRedirect: 302 redirect address를 보내고 다시 browser가 그 주소로 요청


RequestDispatcher.forwardResponse.sendRedirect

brower가 redirection을 알 수 없다 알 수 있다
other context로 보낼수 없다 있다
extra network call 발생안함 발생함
  • RequestDispatcher.forward: request를 다른 servlet으로 보냄
  • RequestDispatcher.include: response가 다른 servlet에 포함되도록 보냄

Servlet attributes (!=init parameters defined in web.xml)

  • request scope: ServletRequest provide methods to get/set/remove attributes
  • session scope: HttpSession 
  • application scope: ServletContext 
반응형

'java, spring' 카테고리의 다른 글

Quartz  (0) 2022.04.19
Tomcat's directories  (0) 2021.03.03
tomcat  (0) 2021.03.02
spring-boot profile별 실행  (0) 2020.03.25
java time - Instant, LocalDate  (0) 2020.03.16
반응형

Install

 Component

  • Catalina

    • servlet container

    • Manages the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access-rights

  • Coyote

    • Connector component for Tomcat that supports the HTTP 1.1 protocol as a web server

    • Listens for incoming connections to the server on a specific TCP port and forwards the request to the Tomcat Engine to process the request and send back a response to the requesting client

  • Jasper

    • JSP engine
    • Parsed JSP files to compile then info JAVA code as servlets
    • Detects changes to JSP files and recompiles them

 Application deploy 방법 3가지

  1. Appication Manager
    • conf/tomcat-users.xml에서 name/password 설정한 후, 
      • <role rolename="manager-gui"/><user username="설정" password="설정" roles="manager-gui"/>
    • tomcat default 화면 GUI에서 다음 사항들을 설정함으로 deploy 가능
      • context path - application의 상위 공통 path
      • XML configuration file URL
      • WAR or Directory URL
  2. Application directory를 통한 deploy
    • conf/server.xml에서 application deploy되는 경로 세팅가능 - 기본경로는 webapps
      • <Host name="localhost" appBase="webapps" unpackWARs="true" audoDeploy="true">
  3. context.xml을 통한 deploy
    • conf/context.xml
    • conf/[engine name]/[host name]/context.xml.default → conf/catalina/localhost/[contextName].xml
    • <Context path="" docBase="deployed application 소스가 있는 경로".../> path="sample"가 context path로 연결되는 듯(ip:8080/sample) 했으나 또 아니라고 함;;;;모지;;;[contextName].xml명에서 [contextName]이 연결된다고...
    • webapps밑에 deployed application가 있지 않고 지정한 docBase에 있는 걸 사용함

 JDBC 연동

    • context.xml <Resource ...>에 설정정보를 추가함

          default value
      maxActive 최대 connection 값 100
      maxIdle 최대 idle connection 허용치 maxActive
      minIdle 최소 idle connection 허용치 initialSize
      initialSize connection pool 최초 생성 갯수 10
      maxWait connection얻기위한 최대 대기시간 30000(ms) 30sec?
      removeAbandoned 특정시간동안 사용하지 않는 connection 반환 false
      removeAbandonedTimeout ??위의 특정 시간이 아닌지?? 60sec
      logAbandoned connection remove될 때 log 기록 여부 false
      testOnBorrow getConnection()수행할때 유효성 테스트할지 여부 false
      validationQuery 테스트할 쿼리, select 1 null

      JDBC driver

      • setenv CLASSPATH=/app/lib/jdbc.jar로 경로 추가해도 되고
      • CATALINA_HOME/lib/jdbc.jar로 직접 lib에 jar파일 추가해도 됨

 Virtual host 

  • apache에서 지원하는 기능인데 tomcat에서도 지원함

  • 여러 domain이 하나의 tomcat에서 작동하도록 해줌 

  • 설정방법

    • Tomcat GUI Manager>Host Manager 클릭

      • <role>에 admin-gui 추가해야함 
        localhost는 기본적으로 떠있어야 하지만
        그외에 host는 내렸다 올렸다 할 수 있음

    • host 구성

      • server.xml

      • <Engine name="Catalina" defaultHost="localhost"> -> 기본적으로 localhost의 내용이 전달됨

 Web server 연동

  • 연동목적
    • 동적요청 분산
    • 정적/동적 처리 -  소스분산
  •  mod_jk
    • AJP 프로토콜을 사용하여 톰캣과 연동하기 위해 만들어진 모듈
    • AJP(Apache Jserv Protocol)는 웹 서버 뒤에있는 웹 애플리케이션 서버(Web Application Server, WAS)으로 들어오는 요청을 웹 서버로 위임할 수 있는 바이너리 프로토콜이다. Apache HTTP Server(이하 Apache)는 80포트로 들어오는 요청 중, 서블릿을 필요로 하는 요청은 Apache Tomcat(이하 Tomcat)에 접속하여 처리한다. (https://joont.tistory.com/55)
    • mod_proxy, mod_proxy_balancer도 사용가능하지만 대표적으로 mod_jk를 많이 사용
    • 설정방법
      • mod_jk 모듈 다운로드 & 설정
        • 압축풀고 컴파일하면 mod_jk.so 생성
        • (window) 컴파일 하려면 visual studio있어야 함, 윈도우 버젼이 몇개 안되다 보니 컴파일된 binary dll이 공유됨
        • (linux) tar.gz 압축파일 받은 후 다음 과정 거치면 됨

          $ tar xvfz tomcat-connectors-1.2.40-src.tar.gz

          $ cd ~/Downloads/tomcat-connectors-1.2.40-src/native

          $ ./configure -with-apxs=APACHE_HOME_DIR/bin/apxs (apxs 옵션은 아파치 설치 디렉토리/bin/apxs를 지정)

          $ make

          $ make install -> 이렇게 하면 Apache_home_dir/modules/mod_jk.so가 생성됨

        • 생성된 mod_jk.so를 아파치에 로딩

          • httpd.conf에 <IfModule jk_module>...와 설정값들 추가

            <IfModule jk_module>

            JkWorkersFile   conf/workers.properties  //꼭 workers.properties 파일명이 아니어도 되지만 일반적 이름쓰자!

            JkLogFile       logs/mod_jk.log

            JkLogLevel      info

            JkMountFile     conf/uri.properties

      • worker를 정의 (workers.properties)
        • worker.[worker_name].[type_option]=[정의]

          worker.list=loadbalancer

          worker.worker1.type=ajp13

          worker.worker1.host=192.168.0.10

          worker.worker1.port=8009

          worker.worker1.lbfactor=1

           

          worker.worker2.type=ajp13

          worker.worker2.host=192.168.0.11

          worker.worker2.port=8010

          worker.worker2.lbfactor=1 //로드밸런스의 가중치 work1,2 둘다 1이므로 1:1

           

          worker.loadbalancer.type=lb

          worker.loadbalancer.balance_workers=worker1, worker2

      • 톰캣이 처리할 요청을 정의
        • httpd.conf에 직접 추가하거나 uri.properties같은 별도 파일로 분리할 수도

          /*.do=worker1

          /*.jsp=worker2

          /servlet/*=loadbalander

           

  • 클러스터
    • 장애 극복: 장애가 난 쪽에는 요청은 전달하지 않도록 Failover 기능 제공
    • WAS 장애나면 Http session도 끊어져 버림
    • 그것을 방지하기 위해 클러스터 사용함
    • Http session을 각 WAS마다 주기적으로 복사함
    • cluster 설정방법
      • server.xml <Cluster className=org.apache.catalina.ha.tcp.SimpleTcpCluster/> 주석 해제만 해주면 됨
        • 나머지 값들은 기본값으로 적용됨
        • 자세한 옵션은 /docs/cluster-howto.html을 참고하라고 하지만 복잡;;;
        • tomcat 5.5 <Cluster> 디스트립터를 참고하면 쉽게 상세 옵션을 알 수 있음!
        • 옵션중에서 mulicast, receiver내용 알아두면 좋음
          • 누가 내 cluster인지 알려면 multicast IP,port가 동일해야 함
          • 한 서버에서 여러 톰캣을 사용할 때 nio receiver의 IP는 겹치면 안되므로 다르게 설정해야 함
      • WEB_INF/web.xml <distributable/> 디스트립터 추가해야 tomcat cluster의 대상으로 인지됨

 

 Thread

  • Thread는 기본적으로 Connector마다 지정하도록 되어 있음
    • <Connector port=8080 protocol=HTTP/1.1...
    • <Connector port=8009 protocol=AJP/1.3...
    • Default Max Thread Value=200, 즉 지정안하면 200
  • connector마다 지정하면 비효율적이므로 shared executor를 사용하여 전체 connector가 공통의 thread pool을 사용할 수 있음
    • <Executor name=tomcatThreadPool ...
    • <Connector executor=tomcatThreadPool...로
  • Thread Dump
    • 서비스에 대한 지연이 생길경우 Thread 상황 분석할 수 있도록 정보남기는 것
    • trace형태(아래에서 위)로 확인 가능
    • 실행 방법 
      • command를 통해서
        1. <pid>확인
          • (unix/linux) ps-ef |grep java |grep tomcat
          • (window) ???
        2. Thread Dump 발생시키기
          • (unix/linux) kill -3 <pid>
          • (window) JAVA_HOME/bin/jstack <pid>
        3. 확인: catalina.out에 로그남음
      • jvisualVM tool이용

 Monitoring

  • Tomcat default Manager
    • GUI manager
    • admin: tomcat 5.5에서만 지원
  • Probe
    • 람다-probe였는데 google에서 지원하면서 psi-probe로 이름변경
    • probe.war를 배포하고 manager user를 활성화해야 함
    • 배포하면 http://ip:port/probe 활성화됨
    • default manager보다 많은 정보 제공
    • 데이터를 수치로 표현, 쓰레드 강제종료 기능 있음
    • cluster 모니터링기능 5.5에만, 8.0지원안함, 201303이후 업데이트 없음
  • jkstatus
    • 아파치와 톰캣 연동하면 아파치에서 보내는 요청에 대해 분석해줌
    • mod_jk에 들어있음
    • worker.properties, uri.properties에 추가
    • 설정하면 http://ip:port/jkstatus 활성화됨
  • JDK tools
    • visualVM
      • jvm에 대한 것 전반적으로 모니터링 가능
      • jdk1.6.0_18부터 지원
      • 장점 - 많은 plugin 지원, mbean 같은 plugin 설치하면 dataSource도 분석가능
      • remote - 원격지에 있는 서버 모니터링 가능
        • JMX 
          • setenv에 CATALINA_OPTS="-Dcom.sun.management.jmxremote...." 추가해야 함
          • JAVA_OPTS로 추가하면 jvm 기동될 때와 shutdown될 때 모두 읽어들임 shutdown될때에도 Dcom.sun.management.jmxremote.port=18080 이런 속성을 읽어들이면 tcp port가 겹쳐서 shutdown이 안될 수도 있으므로 JAVA_OPTS를 사용하지 말자 
          • CATALINA_OPTS는 tomcat기동될 때만 읽히므로 CATALINA_OPTS를 이용하자
          • 간혹 tomcat이 JMX connection 거부할 때가 있는데 그럴때는 다음과 같이 설정하면 됨
            • CATALINA_OPTS="-Dcom.sun.management.jmxremote...."..2줄만 추가
            • in server.xml 
              • <Server port=8005 shutdown=SHUTDOWN>
              • <Listener className=org.apache.catalina.mbeans.JmsRemoteLifecycleListener...
            • CATALINA_HOME/lib/catalina-jmx-remote.jar추가
            • service:jmx:rmi://192.168.56.101:10002/jndi/rmi://192.168.56.101:10001/jmxrmi 로 연결해보자
        • jstatd: java status daemon을 띄워서 사용하는 방법
    • JMC: Java Mission Control
      • jdk1.7.0부터
      • jdk에 포함되지 않고 java...무슨 kit에 포함되었다가 oracle에 합병되면서 추가되었다고 함
        • GC policy에 따라 보여주는 방식 달라짐 CMS방식을 썼을 때 필요한 모니터링 방식이 바뀜
      • G1GC도 가능
  • APM: Application Performance Manager
    • ex) Jennifer,
    • RHQ - JBoss 모니터링하기에 좋음, 무료
      위의 모니터링 툴과 APM과의 차이는 모니터링 데이터를 저장할 수 있다는 점(DB와의 연동을 제공해서 장기적으로 관리가능), 장기적으로 보관해서 비교분석 가능
      but RHQ는 jBoss plugin은 잘 지원하지만 tomcat과 연동해서 사용하기는 부족한듯함

 Tip

  • directory
    • 한 서버에 여러 tomcat 기동할 때 catalina_home 경로를 {catalina_home}/app/Tomcat_01,02,03처럼 여러개 만드는게 좋음
  • setenv
    • 기본 스크립트(catalina.sh, start.sh,shutdown.sh...)수정은 비추  migration한다던게 하면 불편해짐, setenv적극 활용하자
  • 실행유저
    • ROOT는 막자! ROOT로 기동하다가 다른 user로 변경하면 권한 등 문제가 생김
    • server.xml
      • <Server port=8005 shutdown=SHUTDOWN
      • <Listener className=org.apache.catalina.security.SecurityListener checkedOsUsers=root >
      • 이렇게 하면 root로 기동못함
  • Connector
  • option설명
    acceptCount=10 request Queue의 길이를 정의 idle thread가 없으면 queue에서 idle thread가 생길때까지 요청을 대기하는 queue의 길이 default값은 매우 큼, 이걸 작게 잡아두면 기다리지 않고 빨리 에러를 보내게 됨 (요청을 처리할 수 없는 상황이면 빨리 에러 코드를 보내고 싶을 때
    enableLookups=false 기본값은 true Servlet/JSP 코드 중에서 들어오는 http request에 대한 ip를 조회하는 명령등이 있을 경우 DNS 이름을 IP주소로 바꾸기 위해서 DNS 서버에 look up 요청을 보냄 false로 하면 서버간의 round trip발생 방지 가능
    compression=off HTTP message body를 gzip 현태로 압축해서 리턴하지 않음 과거에는 대역폭이 낮아서 압축해서 많이 보냈지만 요즘은 압축하고 푸는 리소스가 더 많음
    maxConnection=8192 하나의 tomcat 인스턴스가 유지할 수 있는 connection의 수 현재 연결되어 있는 실제 connection의 수가 아니라 현재 사용중인 socket fd(file descriptor)의 수 socket과 file이 열리는 갯수
    maxKeepAliveRequest=1 HTTP 1.1 Keep Alive Connection을 사용할 때 최대 유지할 connection수를 결정 Keep Alive를 사용할 환경이 아닌 경우에 1로 두면 됨 톰캣만 사용하거나 다양한 유저가 있을 때에는 1로 하는게 좋음 항상 같은 유저가 들어온다는 보장이 없을 때는 keep alive하지 않고 매번 새로 들어올 수 있게 하는 게 좋음
    tcpNoDelay=true TCP 프로토콜은 기본적으로 패킷을 보낼 때 바로 보내지 않음 버퍼사이즈에 데이터가 모두 담길 때까지 패킷 전송을 보류함으로 대기 시간이 발생하는 것을 방지 트래픽이 증가하지만 현재 망 속도를 고려하였을 때 문제가 크지 않음

 

 

반응형

'java, spring' 카테고리의 다른 글

Tomcat's directories  (0) 2021.03.03
Java Web Application  (0) 2021.03.02
spring-boot profile별 실행  (0) 2020.03.25
java time - Instant, LocalDate  (0) 2020.03.16
Lombok  (0) 2020.02.14
반응형

WAS

  • mvn spring-boot:run -Dspring-boot.run.profiles=local -> bash shell(git bash in Windows)에서만 작동하는듯
  • ./mvnw spring-boot:run -Dspring.profiles.active=local
  • SPRING_PROFILES_ACTIVE=local ./mvnw
  • 이게 안되면 mvn spring-boot:run으로 빌드후 배너만 나오고 이후 반응없음 

Jar

  • java -jar -Dspring.profiles.active=local xxx.jar(jar file path)
반응형

'java, spring' 카테고리의 다른 글

Java Web Application  (0) 2021.03.02
tomcat  (0) 2021.03.02
java time - Instant, LocalDate  (0) 2020.03.16
Lombok  (0) 2020.02.14
Log4j  (0) 2020.02.13
반응형

@RequestParam(value = "date", required = false) @DateTimeFormat(pattern = "yyyyMMdd") LocalDate date) 동작

@RequestParam(value = "date", required = false) @DateTimeFormat(pattern = "yyyyMMdd") Instant date) 에러

Instant로는 yyyymmdd로 받을 수가 없는 듯

 

how to check available timezone

Set<String> zoneIdSet = ZoneId.getAvailableZoneIds();

for(String zoneId:zoneIdSet) System.out.println(zoneId);

 

하루 더하기

[LocalDate] date.plusDays(1)

[Instant] time.plus(1, ChronoUnit.DAYS), time.plus(Duration.ofDays(1))

 

LocalDate -> Instant 변환

ZoneId timezone = ZoneId.of("UTC");// ZoneId.systemDefault()->KST+9

date.atStartOfDay(timezone).toInstant();

반응형

'java, spring' 카테고리의 다른 글

tomcat  (0) 2021.03.02
spring-boot profile별 실행  (0) 2020.03.25
Lombok  (0) 2020.02.14
Log4j  (0) 2020.02.13
ChannelGenre enum관련 에러 (patch시 No validator could be found for constraint)  (0) 2020.01.14
반응형
반응형

+ Recent posts