Kotlin(코틀린)은 JetBrains에서 제작된 프로그래밍 언어로서 구글에서 Android 기본 언어로 채택 되면서 주목받는 hot한 언어가 되었다.

JetBrains의 연구소가 있는 러시아 상트페테르부르크에 있는 코틀린 섬에서 이름을 따왔다고 한다...

 

본 포스팅에서는 Kotlin에서 Class를 만들고 상속받고 사용하는 방법에 대해서 기술하도록 한다.

 

먼저 가장 간단하게 Class 만들기

class Animal

중괄호도 필요 없다. 내용은 비었지만-_- 어쨌건 class 는 class다.

 

그렇다면 Class 사용하는 방법은?

val myAnimal = Animal()

new가 필요 없는 것에 주목.. Kotlin은 class 생성시 new 키워드를 사용하지 않는다.

 

내용이 비었으니 이제 내용을 채워보자. 

Class는 Class 이름, Attribute(member 변수, Property)와 Operation(method)로 구성된다.

 

먼저 Property를 추가...(Kotlin에서는 Attribute를 Property라고 부른다)

다리갯수(nLeg)와 색깔(color)를 추가하며, type 은 nLeg는 Int, color는 String으로 선언한다.

class Animal {
    val nLeg:Int = 4
    val color:String = "yellow"
}

 

Kotlin에서는 class에 기본 getter/setter를 만들어줄 필요가 없다.

val myAnimal = Animal()

println("Number of Leg is ${myAnimal.nLeg}")
println("Color is ${myAnimal.color}")

실행결과는?

Number of Leg is 4
Color is yellow

 

 

IntelliJ에서 Kotlin으로 개발을 하게 되면 Decompiler라는 기능을 통해서 Java로 변경된 code를 확인할 수 있는데, Class에 member만 추가하고 getter/setter가 없어도, Decompiler상에서는 getter/setter가 생성이 된다. 단, val로 선언된 변수의 경우 getter만 생성된다..

Decompiler를 실행하는 방법은 아래 포스팅 참조...

IntelliJ에서 Decompiler를 이용하여 Kotlin을 Java code로 확인하기

 

 

public final class Animal {
   private final int nLeg = 4;
   @NotNull
   private final String color = "yellow";

   public final int getNLeg() {
      return this.nLeg;
   }

   @NotNull
   public final String getColor() {
      return this.color;
   }
}

Property가 변경가능 한 값이면 val 대신 var로 선언해주면 된다.

class Animal() {
    val nLeg:Int = 4
    val color:String = "yellow"
    var name:String = "Tom"
}

 

&아래와 같이 {class 변수 이름}.{property 이름} 으로 접근하고 수정 가능

val myAnimal = Animal()

println("Name of the Animal is ${myAnimal.name}")
myAnimal.name = "Smith"
println("Name of the Animal is ${myAnimal.name}")

실행결과

Name of the Animal is Tom
Name of the Animal is Smith

 

 

 

이번에는 method를 추가해 보자

Anmial Class에 eat()와 cry() method를 추가 한다.

class Animal() {
    val nLeg:Int = 4
    val color:String = "yellow"
    var name:String = "Tom"

    fun eat(something:String) {
        println("Eat $something")
    }

    fun cry() {
        println("Cry!!!")
    }
}

확인해보면...

val myAnimal = Animal()

myAnimal.cry()
myAnimal.eat("apple")
Cry!!!
Eat apple

 

 

본 포스팅의 소스는 아래 github에서 확인 가능하다

https://github.com/jeng832/blog-example/tree/master/21_Kotlin%EC%97%90%EC%84%9C%20Class%20%EC%84%A0%EC%96%B8%ED%95%98%EA%B8%B0

Spring을 처음 접해본 사람들이 공통적으로 느끼는 막막함은 아마 최초에 아무것도 없을 때 어떻게 초기 Project를 시작하느냐 일 것이다. 나 또한 예전에 그랬던 기억이 있어서,

이걸 정리하거나 해두면 좋겠다고 항상 생각했으나 생각만했고...-_-

이번 기회에 글로 적어두고 github에 따로 template 형태를 유지하여 향후 필요시 git을 통해 해당 틀만 가져가도록 만들어두면 좋겠다고 생각이 들었다.

 

이 글은 Eclipse STS에서 Spring-boot를 최초로 생성하고 기본 API를 추가 하는 방법을 적어보겠다.

 

0. 개발 환경 설정

Eclipse를 통한 개발환경 구축은 jdk 설치, Eclipse STS 설치, 환경설정 등 작업이 필요하지만, 이 글의 성격과 맞지 않으므로 따로 적지는 않고, 추후에 다른 글로 추가 할 예정

 

1. Project 생성

File > New > Project... > Spring Boot > Spring Starter Project 선택

2. 기본 Project 설정

Gradle 환경을 이용할 것이고, java8을 활용 그 외 버전이나 package명 등 입력

Project 생성 이후에 build.gradle 파일에서 dependency를 추가해도 되지만, STS에서 미리 선택해서 추가 할 수 있다.

아래 드롭다운 메뉴들을 보면 생각보다 다양한 선택을 할수가 있으니, 적절히 필요한 dependency를 추가할 수 있다.

여기서는 spring-boot 시작과 간단한 API 만들기가 목적이므로 Spring Web을 선택했다.

그렇게 Finish 버튼을 누르면 자동으로 기초적인 spring-boot project가 생성된다.

 

초기 파일 구조는 아래와 같이 매우 간단... 

 

초기 build.gradle 파일은 아래와 같을 것이다.

plugins {
    id 'org.springframework.boot' version '2.1.8.RELEASE'
    id 'io.spring.dependency-management' version '1.0.8.RELEASE'
    id 'java'
}

group = 'org.ijeee.spring'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

spring-boot-starter-web 이 자동으로 dependency에 추가 된 것 확인 가능

 

3. gradle refresh

이제 본격적으로 코드를 작성해야 하지만 잠깐 시작하기 전에 gradle refresh를 한번 해준다.

refresh를 통해 local repository에 dependency가 있는 jar들을 미리 다운받아서 향후 빨간줄(?!)의 귀찮음과 자동완성의 편리함을 도모하자.

4. Controller 추가

controller package를 추가 하고 실제 API를 정의할 Controller class를 추가 한다.

향후 API의 목적에 따라서 Controller class를 분류하여 다수의 class를 생성하는 것도 가능하다.

 

5. API 정의

package org.ijeee.spring.controller;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    @RequestMapping(value="/health", method=RequestMethod.GET)
    public ResponseEntity<?> health() {
        return ResponseEntity.ok().build();
    }
}

ApiController는 @RestController annotation을 이용하여 spring framework에 Controller임을 명시해준다.

 

Class에 실제 호출되는 각 API 별로 public method를 정의 해주고

@RequestMapping annotation을 통해 해당 API의 uri와 HTTP method를 지정한다.

 

위의 예시는 가장 간단한 health check에 활용할 수 있는 method 이다.

 

 

위 내용을 응용해서 CRUD에 해당하는 method를 간단히 작성해 보면 아래와 같다.

package org.ijeee.spring.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ApiController {

    private List value = new ArrayList ();
    @RequestMapping(value="/health", method=RequestMethod.GET)
    public ResponseEntity<?> health() {
        return ResponseEntity.ok().build();
    }

    @RequestMapping(value="/value/index/{index}", method=RequestMethod.GET)
    public ResponseEntity getValue(@PathVariable Integer index) {
        return new ResponseEntity(value.get(index), HttpStatus.OK);
    }

    @RequestMapping(value="/value/elem/{element}", method=RequestMethod.PUT)
    public ResponseEntity<?> postValue(@PathVariable Integer element) {
        this.value.add(element);
        return ResponseEntity.ok().build();
    }

    @RequestMapping(value="/value/index/{index}/elem/{element}", method=RequestMethod.POST)
    public ResponseEntity<?> postValue(@PathVariable Integer index, @PathVariable Integer element) {
        this.value.add(index, element);
        return ResponseEntity.ok().build();
    }
	
    @RequestMapping(value="/value/index/{index}", method=RequestMethod.DELETE)
    public ResponseEntity<?> deleteValue(@PathVariable int index) {
        this.value.remove(index);
        return ResponseEntity.ok().build();
    }
}

 

로직은 대충 적어서 의미가 없고 @RequestMapping을 이용하여 method를 정의하고 @PathVariable을 통해 RESTful한 uri를 만들 수 있음을 파악하면 기본적인 API 정의는 완료~!

MongoDB의 Connection Pool은 MongoDB Java Driver에서 지원된다.


connection string에서 option 있는데 maxPoolSize option 통해서 pool size 지정할수 있음

mongodb://host:27017/?replicaSet=rs0&maxPoolSize=200


connection pool 관련 uri option은 아래와 같다.

 Connection pool configuration:

  • maxPoolSize=n: The maximum number of connections in the connection pool.
  • waitQueueMultiple=n : this multiplier, multiplied with the maxPoolSize setting, gives the maximum number of threads that may be waiting for a connection to become available from the pool. All further threads will get an exception right away.
  • waitQueueTimeoutMS=ms: The maximum wait time in milliseconds that a thread may wait for a connection to become available.


전문은 아래 참조

http://api.mongodb.com/java/3.0/?com/mongodb/MongoClientURI.html

'Development > Database' 카테고리의 다른 글

MongoDB 기본 명령어  (0) 2019.10.19
MongoDB Ubuntu에 설치하기  (0) 2017.02.10
MongoDB 에서 admin 만들기  (2) 2017.02.10

MongoDB 64-bit LTS 공식 지원(12.04, 14.04, 16.04)

 

기본 ubuntu에서 apt-get으로 나오는 mongodb, mongodb-clients, mongodb-server 깔지 말것

 

1. GPG key 받기

sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6


sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4


2. MongoDB source list 추가

Ubuntu 16.04

 echo "deb [ arch=amd64,arm64 ] http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

 Ubuntu 12.04

 echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu precise/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

 Ubuntu 14.04

 echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu trusty/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list

 Ubuntu 18.04 echo "deb [ arch=amd64 ] http://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.0 multiverse"|sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list



3. apt-get 목록 update

$ sudo apt-get update 


4. 설치

$ sudo apt-get install mongodb-org


5. MongoDB 시작

$ sudo service mongod start



참조: https://docs.mongodb.com/manual/tutorial/install-mongodb-on-ubuntu/

'Development > Database' 카테고리의 다른 글

MongoDB 기본 명령어  (0) 2019.10.19
MongoDB에서 Connection Pool 구성 하기  (0) 2017.02.13
MongoDB 에서 admin 만들기  (2) 2017.02.10

MongoDB 설치하면 최초에 authentication 없다.

그래서 비밀번호나 id없이 접속하여 어떤 database에도 접근할수 있고 심지어 admin database에도 접근 가능하다. (물론 bindIp 설정을 건드리지 않았다면 local에서 만 접근 할수 있지만, 어쨌건 접근만 가능하면 login과정없이 들어가진다.)


설치과정에서 root의 비밀번호를 물어보는 mySql을 보다가 MongoDB를 보면 좀 의아하다..


그리고 그로 인해서 아래와 같은 문제도 발생 가능

 

일주일동안 27,000개 이상의 MongoDB가 랜섬웨어에 감염돼

http://blog.alyac.co.kr/923


-_-)... 잘 모르겠지만 Production에 적용하기 위해서는 DB자체 말고 DB가 설치된 서버에 무엇인가 보안을 위한 조치가 필요할것 같다.


어쨌건 처음에 root나 admin의 개념이 없기때문에 생성해 주어야 하는데, 명시적으로 계정과 비밀번호를 만들고, authentication option enable해주어야 한다.


좀더 자세히 설명하면


1. MongoDB에서 admin 계정 만들기

admin Database에서 createUser 명령어로 admin 계정을 만든다. 계정이름은 admin이 아니어도 상관없음

use admin

db.createUser(
  {
    user
: "admin",
    pwd
: "abc123",
    roles
: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)


2. security.authorization 옵션 enable

sudo로 MongoDB 설정 파일을 수정해야 한다.

$ sudo vi /etc/mongod.conf 


파일이 열렸으면 아래 항목을 추가 한다.

 security:

   authorization: enabled


3. MongoDB 재시작

sudo service mongod restart



Authentication 설정 이후에는 아래와 같은 방법으로 MongoDB에 접근해야 한다.
p옵션 뒤에 비밀번호를 적어주어도 된다.

 $ mongo -u "admin" -p --authenticationDatabase "admin"

MongoDB shell version v3.4.2

Enter password:

connecting to: mongodb://127.0.0.1:27017

MongoDB server version: 3.4.2

>


혹은 shell안에서 login하는 방법은 아래와 같다.

반드시 use admin으로 admin Database로 이동해주어야 한다.

use admin

db.auth("admin", "welcome!" )


그런데... 위와 같이 계정을 만들고 비번을 만들어도 그냥 바로 mongo 라는 명령어로 shell에 접속 가능하다-_- 물론 접근한 이후에 Database에는 접근 불가


비록 admin을 만들었지만, 생성시 role을 admin Database에만 주었으므로, 다른 Database는 접근할 수 없다-_- 

이건 admin도 admin이 아닌것도 아닌.....

다시말하면 위의 과정으로 생성된 계정은 admin Database에 대한 관리 권한을 가지게 되는 것이다.


따라서 실제 data를 저장하기 위한 Database에도 계정을 따로 만들어주어야 한다.

아니면 admin에 다 role을 추가 해주면 되긴 되겠으나..안해봄-_-



'Development > Database' 카테고리의 다른 글

MongoDB 기본 명령어  (0) 2019.10.19
MongoDB에서 Connection Pool 구성 하기  (0) 2017.02.13
MongoDB Ubuntu에 설치하기  (0) 2017.02.10

+ Recent posts