네로개발일기

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

'2022/06'에 해당되는 글 9건


반응형
kill -9로 종료하는 것은 좋지않다. jvm shutdown hook 또는 spring의 @PreDestroy의 실행을 보장하기 힘들다. kill -2(SIGINT) 혹은 kill -15(SIGTERM)을 쓰는 것이 좋다.

kill 명령어와 Graceful Shutdown에 대해서 알아보고자 한다.

 

 kill 명령어 알아보기 

https://frogand.tistory.com/69

 

[Linux] ps 명령어 / kill 명령어 / 프로세스 확인 및 죽이기 / 프로세스 일괄 종료 / kill process

# 프로세스란? 실행중인 프로그램 # ps 명령어 - Process 와 관련 linux 명령어는 ps 입니다. 옵션 기능 -e 시스템 상의 모든 프로세스 정보를 출력 -f 상세한 정보를 출력 (full-format) $ ps -ef UID PID PPID C..

frogand.tistory.com

 

애플리케이션 구동도 중요하지만, 안전한 종료야 말로 신규 버전을 배포하기 위해 필수적으로 진행해야 한다. 

 

Graceful Shutdown이란?

프로그램이 종료될 때, 최대한 side effect없이 로직을 잘 처리하고 종료하는 것을 의미한다.

지속가능한 소프트웨어를 위해 폐기 가능한(Disposability) 시스템을 구성해야 한다. 그리고 소프트웨어의 안전성을 높이기 위하여 graceful shutdow이 필요하다. 프로세스가 갑작스러운 하드웨어 문제에 의해 죽는 상황이 발생하더라도 문제가 없는 견고한 프로그램을 만들어야 한다. 프로그래머는 이를 준비해야 한다. (The Twelve-Factor App 방법론)

 

SIGTERM, SIGKILL 차이점

kill -9 $PID는 강제종료이다. -9인 SIGKILL은 리소스를 정리하는 핸들러를 지정하지 않고 프로세스를 바로 죽인다는 의미이다. 만약, 실행 중인 쓰레드가 있더라도 이를 무시하고 중단하는데 혹시라도 굉장히 중요한 작업중이라면 최악의 상황이 일어날 수 있기 때문이다.

 

 

Spring boot에서는 actuator를 사용해서 graceful shutdown을 할 수 있다.

 

 참고자료 

https://blog.marcosbarbero.com/graceful-shutdown-spring-boot-apps/

 

Graceful Shutdown Spring Boot Applications

This guide walks through the process of graceful shutdown a Spring Boot application. The implementation of this blog post is originally created by Andy Wilkinson and adapted by me to Spring Boot 2. The code is based on this GitHub comment. Introduction A l

blog.marcosbarbero.com

https://heowc.dev/2018/12/27/spring-boot-graceful-shutdown/

 

Spring Boot - 안전하게 종료시키기 | 허원철의 개발 블로그

Spring Boot를 안전하게 종료시키는 방법에 대한 소개이다.

heowc.dev

https://kapentaz.github.io/spring/Spring-Boot-Actuator-Graceful-Shutdown/#

 

Spring Boot Actuator Graceful Shutdown

Spring Boot 환경에서 application을 shutdown 하는 방법 중 대표적인 것이 actuator의 shutdown endpoint 기능을 이용하는 것입니다. 이 endpoint는 예상과 달리 처리 중인 요청이 있더라도 그냥 shutdown 처리를 합니

kapentaz.github.io

 

728x90
반응형
blog image

Written by ner.o

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

반응형

https://www.amcharts.com

 

JavaScript charting library - amCharts 4

The most innovative charting library on the market. Easily add stunning data visualizations to JavaScript, TypeScript, Angular, React, and other apps.

www.amcharts.com

 

Demo에 가보면 예제를 볼 수 있다.

그 중에서 나는 column-with-rotated-series를 사용하였다.

 

 

ajax로 데이터를 가져와서 Chart를 뿌려주는 것을 만들려고 한다.

 

data 형식은 아래와 같다.

var data = [
  {category: "USA", value: 2025}, 
  {category: "China", value: 1882}, 
  {category: "Japan", value: 1809}, 
	... 생략 ... 
  {category: "Germany", value: 1322}];

 

column-chart.js

var ColumnChart = function () {
  this.initEvents();
}

ColumnChart.prototype.initEvents = function () {

}

ColumnChart.prototype.getData = function (url, id) {
  var _this = this;

  $.ajax({
    url: url,
    method: "GET",
    dataType: "json",
    async: false,
    success: function(data) {
      _this.renderChart(id, data)
    },
    error: function(err) {
      alert("적용 중 에러가 발생하였습니다.");
      console.log(err);
    }
  });
}

ColumnChart.prototype.renderChart = function (chartId, data) {
  var root = am5.Root.new(chartId);

  root.setThemes([
    am5themes_Animated.new(root)
  ]);

  var chart = root.container.children.push(
    am5xy.XYChart.new(root, {
      panX: false,
      panY: false,
      layout: root.verticalLayout
    })
  );

  // y좌표 설정
  var yRenderer = am5xy.AxisRendererY.new(root, {});
  yRenderer.labels.template.setAll({
    fontSize: 13 // y좌표 폰트 크기 조정
  });

  var yAxis = chart.yAxes.push(
    am5xy.ValueAxis.new(root, {
      renderer: yRenderer
    })
  );

  // x좌표 설정
  var xRenderer = am5xy.AxisRendererX.new(root, { minGridDistance: 30 });
  xRenderer.labels.template.setAll({
    centerY: am5.p10,
    centerX: am5.percent(50),
    paddingRight: 0,
    fontSize: 13 // x좌표 폰트 크기 조정
  });

  var xAxis = chart.xAxes.push(am5xy.CategoryAxis.new(root, {
    maxDeviation: 0.3,
    categoryField: "category", // 카테고리 명을 적어주면 된다.
    renderer: xRenderer,
  }));

  xAxis.data.setAll(data);

  var tooltip = am5.Tooltip.new(root, {
    labelText: "{valueY}",
    autoTextColor: false // 문자 색상을 설정할 수 있다. autoTextColor: false로 색상 설정을 없앰.
  });

  var series = chart.series.push(
    am5xy.ColumnSeries.new(root, {
      name: "Chart Name",
      xAxis: xAxis,
      yAxis: yAxis,
      valueYField: "value",
      categoryXField: "category", // x좌표 categoryField와 일치시킨다.
      tooltip: tooltip
    })
  );

  series.columns.template.setAll({
    cornerRadiusTL: 5,
    cornerRadiusTR: 5,
    width: 32 // 컬럼의 너비 설정
  });

  // 컬럼 색상 설정 -> 기본으로 설정
  series.columns.template.adapters.add("fill", function (fill, target) {
    return chart.get("colors").getIndex(series.columns.indexOf(target));
  });
  series.columns.template.adapters.add("stroke", function (stroke, target) {
    return chart.get("colors").getIndex(series.columns.indexOf(target));
  });

  series.data.setAll(data);
  chart.set("cursor", am5xy.XYCursor.new(root, {}));
}

 

index.html

<div class="category-chart">
 <div class="row">
  <div class="box">
   <div class="category-name">Category</div>
   <div id="category-chart" class="chart"></div>
  </div>
 </div>
</div>

<script src="https://cdn.amcharts.com/lib/5/index.js"></script>
<script src="https://cdn.amcharts.com/lib/5/xy.js"></script>
<script src="https://cdn.amcharts.com/lib/5/themes/Animated.js"></script>
<script>
    var ColumnChart = new ColumnChart();

    $(function () {
      ColumnChart.getData('/category', 'category-chart'); // ajax로 data를 가져와 chart를 그려준다.
    })
</script>

 

chart.css

.category-chart {
  width: 100%;
}

.box {
  /* width: 48%; */
  background-color: rgba(238, 238, 238, 0.4);
  padding-top: 20px;
  padding-bottom: 16px;
  margin-left: auto;
  margin-bottom: 20px;
  border-radius: 10px;
}

.category-name {
  font-weight: bold;
  text-align: center;
  margin-bottom: 6px;
}

.chart {
  height: 300px; /* height를 꼭 지정해주어야 한다. */
}

 

 

728x90
반응형
blog image

Written by ner.o

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

반응형

Kaminari를 이용한 Pagination 구현

1. Gem 설치

Gemfile 작성

Gem 'kaminari'
$ bundle install

2. Controller에서 내용 추가

class PostsController < ApplicationController
    def index
        @posts = Post.order("created_at DESC").page params[:page]
    end
end

3. 한 목록당 게시물 갯수 설정

class Post < ApplicationRecord 
    paginates_per 5
    ...
end

혹은

class PostsController < ApplicationController
    def index
        @posts = Post.order("created_at DESC").page(params[:page]).per(5)
    end
    
    def show
        @posts = Post.page(params[:page]).per(10)
    end
end

이런 식으로 paginate 정의를 해준다.

 

index.html.erb 파일에서 아래 태그를 삽입하면 목록 번호가 뜬다.

<%= paginate @posts %>

 

kaminari에 디자인 템플릿 적용

https://github.com/felipecalvo/bootstrap5-kaminari-views

 

GitHub - felipecalvo/bootstrap5-kaminari-views: Bootstrap 5 compatible styles for Kaminari. Tested on Bootstrap 5.0.1.

Bootstrap 5 compatible styles for Kaminari. Tested on Bootstrap 5.0.1. - GitHub - felipecalvo/bootstrap5-kaminari-views: Bootstrap 5 compatible styles for Kaminari. Tested on Bootstrap 5.0.1.

github.com

kaminari에 디자인 템플릿을 적용할 수 있다.

728x90
반응형
blog image

Written by ner.o

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

반응형

스프링을 이해하려면 POJO 기반으로 스프링 삼각형이라는 애칭을 가진 IoC/DI, AOP, PSA라고 하는 스프링의 3대 프로그래밍 모델에 대해 이해가 필수다.

 

IoC/DI - 제어의 역전/의존성 주입

프로그래밍에서 의존성이란 무엇일까?

예를들어) 운전자가 자동차를 생성한다. -> 자동차가 내부적으로 타이어를 생산한다. (운전자 -> 자동차 -> 타이어) 의존

-> 전체(의존하는 객체)가 부분(의존되는 객체)에 의존한다.

 

집합(Aggregation) 관계: 부분이 전체와 다른 생명 주기를 가질 수 있다.

구성(Composition) 관계: 부분은 전체와 같은 생명 주기를 갖는다.

interface Tire {
    String getBrand();
}

public class KoreaTire implements Tire {
    public String getBrand() {
        return "한국 타이어";
    }
}

public class AmericaTire implements Tire {
    public String getBrand() {
        return "미국 타이어";
    }
}

public class Car {
    
    Tire tire;
    
    public Car() {
        tire = new KoreaTire(); // Car 클래스는 Tire 인터페이스 뿐만 아니라 KoreaTire 클래스도 의존하게 된다.
    }
    
    public String getTireBrand() {
        return "장착된 타이어: " + tire.getBrand();
    }

 

1. 생성자 주입

public class Car {
    Tire tire;
    
    public Car(Tire tire) { // 생성자 주입
        this.tire = tire;
    }
    
    public String getTireBrand() {
        return "장착된 타이어: " + tire.getBrand();
    }
}

public class Driver {
    public static void main(String[] args) {
        Tire tire = new KoreaTire();
        
        Car car = new Car(tire);
        
        System.out.println(car.getTireBrand());
    }
}

의존성 주입을 이용함으로써 자동차가 구체적인 객체를 생성하고 연결하는 것이 아니라 운전자가 대신 원하는 의존성을 생성하고 연결해준다.

 

따라서, Car 객체는 의존성 주입을 통해 추상적인 인터페이스에 의존하면서 실행이 가능해진다. Car 객체는 수정없이 확장이 가능해진다.

 

생성자 주입 방식의 장점

- 의존 관계 설정이 되지 않으면 객체 생성 불가 -> 컴파일 타임에 인지 가능 NPE 방지

- 의존성 주입이  필요한 필드를 final로 선언하여 Immutable한 객체로 만들 수 있음

- 순환 참조 감지 기능 -> 순환 참조시 앱 구동 실패

- 테스트 코드 작성 용이 (독립적으로 인스턴스화가 가능한 POJO(Plain Old Java Object)여야 하는 것이다. DI 컨테이너를 사용하지 않고도 단위 테스트에서 인스턴스화할 수 있어야 한다.)

 

2. 속성 주입

@Autowired를 통한 의존성 주입

@Autowired Tire tire를 사용하여 설정자 메서드를 사용하지 않고도 스프링 프레임워크가 설정파일을 통해 설정자 메서드 대신 속성을 주입해준다.

 

@Resource를 통한 속성 주입

@Resource는 @Autowired와 같이 속성을 자동으로 엮어준다. @Autowired는 스프링의 어노테이션이고 @Resource는 자바표준 어노테이션이다.  

 

AOP - Aspect 관점 핵심 관심사 횡단 관심사

AOP - 관점지향 프로그래밍

스프링 DI가 의존성에 대한 주입이라면 AOP는 로직에 대한 주입이다.

 

여러 모듈에서 발생하는 공통적인 부분 -> 횡단 관심사

AOP 로직 주입이 가능한 부분

Around(메서드 전 구역), Before(메서드 시작 전), After(메서드 종료 후), After Returning(메서드 정상 종료 후), After Throwing (메서드에서 예외가 발생하면서 종료된 후)

 

스프링 AOP의 핵심

- 인터페이스 기반

- 프록시 기반

- 런타임 기반

 

PSA - 일관성 있는 추상화

서비스 추상화의 예로 JDBC를 들 수 있다. JDBC라고 하는 표준 스펙이 있기에 어떤 DBMS를 사용하든 Connection, Statement, ResultSet을 이용해 공통된 방식으로 코드 작성이 가능하다. 데이터베이스의 종류에 관계없이 같은 방식으로 제어할 수 있는 이유는 디자인패턴에서 설명했던 어댑터패턴을 활용했기 때문이다.

 

다수의 기술을 공통의 인터페이스로 제어할 수 있게 한 것 -> 서비스 추상화

스프링 프레임워크는 서비스 추상화를 위해 다양한 어댑터를 제공한다.

728x90
반응형
blog image

Written by ner.o

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

반응형

자바스크립트를 사용하여 페이지를 새로고침하는 방법이다. 화면 개발을 하다보면 페이지 전체를 불러오거나 특정 영역을 갱신해야 하는 경우에 일반적으로 location을 사용한다. 특정 부분을 갱신하는 경우에는 iframe을 사용하거나 jQuery의 load를 사용하는 것이 좋다.

 

location.reload()

// location을 사용하는 방법
location.reload();
location.replace(location.href);
location.href = location.href;

// history를 사용하는 방법
history.go(0);

location은 페이지의 위치를 나타내기 때문에 location 방식을 권장한다. history는 페이지가 이동한 이력을 정의하고 있다. 

 

// Post 데이터를 포함해 페이지를 새로고침한다.
location.reload();

// Post 데이터는 포함하지 않으며 페이지를 새로고침한다.
// 이 때 현재 이력을 수정하며 페이지를 불러오기 때문에 history에 새로운 이력은 추가되지 않는다.
location.replace(location.href);

// 페이지를 이동한다. 이동할 페이지를 현재 페이지로 지정한다.
location.href = location.href;

reload() 함수는 옵션을 주어 실행할 수 있으며, 1개의 boolean 인자를 옵션 값으로 받는다. default 옵션값은 false이다. 

true로 설정하는 경우에는 브라우저가 가지고 있는 캐시를 무시하고 새로운 리소스를 화면에 불러온다.

location.reload(); // default: false

location.reload(true); // 브라우저가 가지고 있는 기존의 리소스는 신경쓰지 않고 새로운 리소스를 받아 화면을 갱신합니다.

 

location

location은 현재 Document에 대한 위치를 가지고 있는 객체로 location이나 window.location 또는 document.location를 통해서 접근이 가능하다.

 

location, window.location, document.location를 일치 연산자를 이용하여 비교해보면 동일하다는 것을 알 수 있다.

location === window.location // true
window.location === document.location // true

location, window.location, document.location은 동일하기 때문에 브라우저간의 호환성 문제가 있어 location의 사용에 문제가 있는 경우 아래와 같은 방법으로 페이지를 새로고침할 수 있다.

function reload() {
    (location || window.location || document.location).reload();
}
728x90
반응형
blog image

Written by ner.o

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