2022. 2. 2. 22:14ㆍJava
날짜 연산
https://codechacha.com/ko/java-examples-add-two-dates/
String day = "20220101";
DateFormat df = new SimpleDateFormat("yyyyMMdd");
try {
Calendar cal = Calendar.getInstance();
cal.setTime(df.parse(day));
cal.add(Calendar.DATE, 1);
day = df.format(cal.getTime());
} catch(ParseException e) {
e.printStackTrace();
}
문자열 날짜형으로 변경
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHH:mm:ss");
String strDate = day + time;
Instant date = null;
try {
date = sdf.parse(strDate).toInstant();
} catch(ParseException e) {
e.printStackTrace();
}
Spring Boot에서 system properties 값 참조하기
java -jar -Dtest=xxxx Application.jar
public class Application {
@Value("${test}")
String test;
@GetMapping("/")
String home() {
System.out.println(test);
return "Spring is here!";
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
System.out.println("Start!");
}
}
Spring Boot에서 appliation.properties 변수 참조하기
https://kim-jong-hyun.tistory.com/17
# static으로 선언하면 값을 가져오지 못함
@Value("${quarts.schedule}")
private static String schedule;
@GetMapping("/")
String home() {
logger.info("Quartz Schedule: " + schedule);
return "Spring is here!";
결과
Quartz Schedule: null
logback 사용시, 아래 구문이 빠지면 아래 부분이 작동을 하지 않음
환경설정파일 적용 안됨
콘솔은 잘되나, 파일로 로깅하는 것은 안됨
main 함수에 꼭 필요한 내용
SpringApplication.run(ProcessKill.class, args);
log4j2 셋팅
https://tlatmsrud.tistory.com/31
pom.xml
<!-- https://mvnrepository.com/artifact/org.apache.logging.log4j/log4j-slf4j-impl -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.17.2</version>
</dependency>
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Properties>
<Property name="logNm">rolling</Property>
<Property name="layoutPattern">%style{%d{yyyy/MM/dd HH:mm:ss,SSS}}{cyan} %highlight{[%-5p]}{FATAL=bg_red, ERROR=red,
INFO=green, DEBUG=blue} [%C] %style{[%t]}{yellow}- %m%n</Property>
</Properties>
<!-- 로그 출력 방식 -->
<Appenders>
<!-- 콘솔 출력 방식 -->
<Console name="console-log" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n" />
</Console>
<!-- 파일 저장 방식 -->
<File name="file" fileName="./logs/processKill.log">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</File>
<RollingFile name="rollingFile" fileName="./logs/${logNm}.log" filePattern="./logs/${logNm}_%d{yyyy-MM-dd}_%i.log.gz">
<PatternLayout pattern="${layoutPattern}"/>
<Policies>
<SizeBasedTriggeringPolicy size="300KB"/>
<TimeBasedTriggeringPolicy interval="1"/>
</Policies>
<DefaultRolloverStrategy max="10" fileIndex="min"/>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="moniter.PrinterClient" level="DEBUG"></Logger>
<Root level="DEBUG">
<appender-ref ref="console-log" level="DEBUG" />
<appender-ref ref="file" level="INFO" />
<appender-ref ref="rollingFile" level="INFO" />
</Root>
</Loggers>
</Configuration>
<Loggers>
<Logger name="moniter.PrinterClient" level="DEBUG"></Logger>
<Root level="DEBUG">
<appender-ref ref="console-log" level="DEBUG" />
<appender-ref ref="file" level="INFO" />
</Root>
</Loggers>
</Configuration>
한글깨짐 문제 찾기
System.out.println("-->" + new String(e.getMessage().getBytes("UTF-8"), "EUC-KR"));
System.out.println("-->" + new String(e.getMessage().getBytes("UTF-8"), "KSC5601"));
System.out.println("-->" + new String(e.getMessage().getBytes("UTF-8"), "x-windows-949"));
System.out.println("-->" + new String(e.getMessage().getBytes("UTF-8"), "iso-8859-1"));
System.out.println("-->" + new String(e.getMessage().getBytes("KSC5601"), "EUC-KR"));
System.out.println("-->" + new String(e.getMessage().getBytes("KSC5601"), "UTF-8"));
System.out.println("-->" + new String(e.getMessage().getBytes("KSC5601"), "x-windows-949"));
System.out.println("-->" + new String(e.getMessage().getBytes("KSC5601"), "iso-8859-1"));
System.out.println("-->" + new String(e.getMessage().getBytes("x-windows-949"), "EUC-KR"));
System.out.println("-->" + new String(e.getMessage().getBytes("x-windows-949"), "KSC5601"));
System.out.println("-->" + new String(e.getMessage().getBytes("x-windows-949"), "UTF-8"));
System.out.println("-->" + new String(e.getMessage().getBytes("x-windows-949"), "iso-8859-1"));
System.out.println("-->" + new String(e.getMessage().getBytes("iso-8859-1"), "EUC-KR"));
System.out.println("-->" + new String(e.getMessage().getBytes("iso-8859-1"), "KSC5601"));
System.out.println("-->" + new String(e.getMessage().getBytes("iso-8859-1"), "x-windows-949"));
System.out.println("-->" + new String(e.getMessage().getBytes("iso-8859-1"), "UTF-8"));
System.out.println("-->" + new String(e.getMessage().getBytes("EUC-KR"), "UTF-8"));
System.out.println("-->" + new String(e.getMessage().getBytes("EUC-KR"), "KSC5601"));
System.out.println("-->" + new String(e.getMessage().getBytes("EUC-KR"), "x-windows-949"));
System.out.println("-->" + new String(e.getMessage().getBytes("EUC-KR"), "iso-8859-1"));
Quartz 변수 넘기기
https://huikyun.tistory.com/231
변수 셋팅
JobDetail jobDetail = JobBuilder.newJob(DashboardDataJob.class)
.build();
CronTrigger trigger = (CronTrigger)TriggerBuilder.newTrigger()
.withSchedule(CronScheduleBuilder.cronSchedule(schedule))
.build();
JobDataMap jobDataMap = jobDetail.getJobDataMap();
jobDataMap.put("port", port);
변수 사용하기
public class DashboardDataJob implements Job {
private static Logger logger = LoggerFactory.getLogger(DashboardDataJob.class);
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
logger.info("DashboardDataJob Start");
JobDataMap jobDataMap = context.getMergedJobDataMap();
String port = jobDataMap.getString("port");
String value = "http://localhost:"+ port +"/insert";
logger.info("URL: "+ value);
try {
URL url = new URL(value);
InputStream is = url.openStream();
is.close();
} catch (java.io.IOException e) {
// TODO Auto-generated catch block
logger.error("execute() Except", e);
}
logger.info("DashboardDataJob End");
}
}
JVM TimeZone 설정
OS의 TimeZone과 JVM의 TimeZone이 다를 경우, 조치하는 방법
1. 실행시 옵션 적용
java -Duser.timezone="Asia/Seoul" -jar abc.jar
2. 환경변수 설정
export TZ="Asia/Seoul"
JAVA_OPTS 처리하기
https://whoa0987.tistory.com/37
# JAVA_OPTS 셋팅
-DrootDir=/bac/bbb/
# JAVA_OPTS 변수 가져오기
public ImageManager(String dir) {
ImagePath.add(System.getProperty("rootDir") + dir);
}
Maven에서 resource 복사하기(이미지, jar 등)
jar 파일안의 jar, image 등은 접근이 안되기 때문에 디렉토리에 복사하여 참조하도록 함
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>lok.Lok</mainClass>
<addClasspath>true</addClasspath>
<classpathPrefix>resources/libs/</classpathPrefix>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.2.0</version>
<executions> <execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<includeScope>runtime</includeScope>
<outputDirectory>${project.build.directory}/resources/libs/</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<id>copy-resource-one</id>
<phase>install</phase>
<goals>
<goal>copy-resources</goal>
</goals>
<configuration>
<outputDirectory>${basedir}/target/resources</outputDirectory>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>*/**</include>
</includes>
</resource>
</resources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
String.split 사용시 유의점
String[] split(String regex)은 입력값은 정규식이기 때문에 주의해야 함
String temp = "abc.txt".split(".");
System.out.println(temp);
위의 결과는 '0'임
정규식으로 인식하기 때문에 '.split("\\.")'으로 표현해야 함
'Java' 카테고리의 다른 글
Class 정보 가져오기 (0) | 2024.07.27 |
---|---|
request 객체 정보 조회 (0) | 2024.07.27 |
pom.xml 셋팅 (0) | 2022.01.31 |
maven 에러 (0) | 2022.01.30 |
java 설치 (0) | 2022.01.30 |