함수

javascript 2023. 3. 27. 20:44

function a() { } 보다 ,    const a = () => {} 로 쓰는게 좋다.

==> 이유 1. function은 생성자인지 함수용도인지 헤깔리지만, const는 항상 함수 용도이다.  생성자가 필요하면 class로 쓰면 된다.

         이유 2. const의 우측 ()=>{} 이걸 변수에 대입하는 느낌으로 array안 이나, 함수 parameter등 동일한 방식으로 사용가능하단.

단,

let object= {

    name: 'kim'

    run : ()=> {}   까지는 굿인데, {}안에서 this는 못 쓰는 문제가 있어, 이때는 function써도 되지만 위 문제들 때문에 그냥
    run() {..}        쓰면 된다.

}

 

 

closure: 내부함수가 외부함수의 변수를 access할 수 있다. (상식수준임) =>  예제코드에선 function이 이너함수를 리턴하는 형태가 많음.

 

Javascript map과 forEach의 차이점.  map은 매번 뭔가를 리턴을 한다. 따라서 array를 map시 새 array가 생긴다.

 

[ CSS 로 이동예정]

CSS specicificity:  인라인 style1순위, ID 2순위, class 3순위, 요소 4순위 => 1,0,0,0 혹은 1000 형태로 표현됨. 0010 은 class임.

 =>  p { color:red;]  .p1 { color:green; } 이면  p는 0.0.0.2 이고  .p1은 0.0.1.0 이라서  .p1이 힘이 우선 적용된다...

   (p가 0.0.0.1이 아니고 0.0.0.2인 이유는 아직 잘 모르겠음)

 

 

 

Posted by yongary
,

spread ...

javascript 2023. 3. 21. 00:00

1. let arr = [ [1,2], [2,3] ]

...arr 은  [1,2], [2,3] 을 의미하지만 직접 사용하지는 못하고 [...arr]이나 {...arr} 등으로 사용가능하다.

 

2. let json = {a:1, b:2}

 ...json 은 a:1, b:2 를 의미하지만 위 예제와는 달리 iterable은 아니라서   {...json}형태로 쓰면 복사효과가 있다.

 

 

1에서 let spread = [].concat( ...arr)
  ==>  spread 는  [1, 2, 2, 3] 이 된다. concat이 여러개 array(iterable)를 수용가능.

 

 

Posted by yongary
,

75가지 질문들 :  REF

 

- clickJacking: 

ClickJacking is an attack which lets the developer fool the users into thinking that they are clicking one thing but actually they are clicking the other one.

- Coercion :  javascript 타입변환으로 자동변환과 강제변환(explict coercion)이 있다.   explict 예:) Number('1') 

 

- IIFE :  즉시 실행함수, 아래와 같이 정의즉시 실행됨.

(function(a, b) { return a + b })(1, 2) // 3

 

- srcset: @media css태그와 유사하게  html img 태그안에서, responsive한 image들 지정.

<img
  srcset="images/heropy_small.png 400w,
          images/heropy_medium.png 700w,
          images/heropy_large.png 1000w"
  src="images/heropy.png" />

 

- Mixin : A Mixin is a code block that lets the group of CSS declarations which we can reuse in our site. 

@mixin set-color {
  color: #fff;
  background-color: yellow;
}
 
h1 {
  @include set-color
}

 

- CSP : Content-Security-Policy : 웹 취약점 중 하나인 XSS등의 공격을 방지하기 위한 보안정책입니다.

<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'none'">
;로 구분을 주어 사용하면 됩니다.

self : 현재도메인의 리소스만 만 사용하겠다는 뜻.
script-src 'none' : 모든 스크립트는 허용암함.
Posted by yongary
,

fail-fast vs fail-safe

java core 2023. 3. 7. 23:34

대부분의 iterator는 fail-fast이다.

작업중 데이터가 바뀐다면 ConcurrentModification Exception이 발생한다.

 

ConcurrentHashMap같은 몇몇 컬렉션타입은 fail-safe iterator를 지원하는데

이는 복제본을 가지고 작업을 하는 방식이라서

메모리 리소스 단점과 데이타가 부정확할 수 있다는 단점이 있다.

 

 

Posted by yongary
,

ERD 무료 툴 (draw.io)

BACK-END 2023. 2. 28. 19:18

erWin이 가격도 문제이고, 공유기능도 없어서 

초기에 스케치용으로 ERD를 그릴때는 draw.io 가 좋은것 같다. 여러명이서 구글드라이브에 공유해 동시에 그릴 수 있는 장점이 있다.

 

TIP: 

https://drawio-app.com/entity-relationship-diagrams-with-draw-io/ 

 

ERD외에도 다양한 diagram을 그릴 수 있는데,

- 어떤 형태의 Diagram이 좋을까는 여기참고: 

https://velog.io/@yooha9621/UML%EB%8B%A4%EC%9D%B4%EC%96%B4%EA%B7%B8%EB%9E%A8UML%EB%8B%A4%EC%9D%B4%EC%96%B4%EA%B7%B8%EB%9E%A8-%EC%A2%85%EB%A5%981

 

 

오라클에서 테이블목록, 엔터티정의서, 테이블정의서 추출 SQL: https://seodaeya.tistory.com/105 

 

# 테이블 목록 조회
SELECT A.TABLE_NAME AS 테이블명 , 
       B.COMMENTS AS 코멘트
  FROM USER_TABLES A
 INNER JOIN USER_TAB_COMMENTS B
    ON A.TABLE_NAME = B.TABLE_NAME
   -- AND A.TABLE_NAME LIKE 'TB_%' -- 네이밍룰 있을경우
   AND INSTR(A.TABLE_NAME,'TEST') = 0  -- TEST 테이블 있으면 제외
 ORDER BY A.TABLE_NAME
 

    
--  테이블 정의서

SELECT
    a.table_name     AS 테이블명,
    --a.tab_cmt        AS 테이블설명,
    a.column_name    AS 컬럼명,
    b.pos            AS PK,
    a.data_type      AS 데이터유형,
    a.DATA_LENGTH    AS 데이터길이,
    a.nullable       AS null여부,
    --,a.column_id      AS 컬럼순서,
    a.data_default   AS 기본값,
    a.col_cmt        AS 컬럼설명
FROM
    (
        SELECT
            s1.table_name,
            s3.comments   AS tab_cmt,
            s1.column_name,
            s2.comments   AS col_cmt,
            s1.data_type,
            CASE
                WHEN s1.data_precision IS NOT NULL THEN
                    data_precision
                    || ','
                    || data_scale
                ELSE
                    to_char(s1.data_length)
            END AS DATA_LENGTH,
            nullable,
            column_id,
            data_default
        FROM
            user_tab_columns    s1,
            user_col_comments   s2,
            user_tab_comments   s3
        WHERE
            s1.table_name = s2.table_name
            AND s1.column_name = s2.column_name
            AND s2.table_name = s3.table_name
            AND S1.TABLE_NAME in (
				SELECT TABLE_NAME from USER_TABLES
    )
    ) a,
    (
        SELECT
            t1.table_name,
            t2.column_name,
            'PK' || position AS pos
        FROM
            (
                SELECT
                    table_name,
                    constraint_name
                FROM
                    user_constraints
                WHERE
                    constraint_type = 'P'
            ) t1,
            (
                SELECT
                    table_name,
                    constraint_name,
                    column_name,
                    position
                FROM
                    user_cons_columns
            ) t2
        WHERE
            t1.table_name = t2.table_name
            AND t1.constraint_name = t2.constraint_name
    ) b
WHERE
    a.table_name = b.table_name (+)
    AND a.column_name = b.column_name (+)
ORDER BY
    a.table_name,
    a.column_id
Posted by yongary
,

react-router-dom

React.js 2023. 2. 25. 20:55

1. 설치는 npm install -save 로  react-router-dom@6 로 하면 6.0.2버전 등이 설치되며 기본사용법은 아래와 같이 <BrowserRouter> 밑에 <Routes>를 두고 그 밑에 여러개의 <Route>를 넣는 방식이다.

 

import {BrowserRouter, Routes, Route> from "react-router-dom"
import SubSystem1 from "./SubSystem1.js" 
import Admin from "./Admin.js"

export default cont HomePage = () => {

	return (
    	<>
        	<BrowserRouter>  //최상단
           		<Routes> //Router 여러개 포함
        			<Route path="/" element={<SubSystem1 />} />   //에전엔 component였는데 6부턴 element로 바뀜
        			<Route path="/admin" element={<Admin />} />
        
        		</Routes>
    		</BrowserRouter>
    	<>
    )

}

 

2. 혹시 첫 페이지에 간단한 링크를 넣고싶다면

<BrowserRouter>와 <Routes>사이에 아래 코드블락 같은걸 넣으면 된다.

Link도 react-route-dom에서 import하는건데,  <a href는 화면을 refresh하면서 가지만 Link는 refresh없이 변경되므로 뛰어나다.

 

 

    <nav>

          <Link to="/"> Home </ Link>

           <Link to="/admin"> admin </Link>   

    </nav>

 

3. <Link> 보다 조금 발전되어 active일 경우 style등을 넣는다던지 className을 넣는다던지 하고싶으면 <NavLink>를 사용하면 된다.  

<NavLink className="myclass" to="/"> Home </NavLink>

 

3.1  className을 좀더 발전시키면 className={({isActive}) => "myClass" + (isActive?"blue":""}

==> 이 경우 styles.scss 를 import를 하고 여기에 아래와 같이 css를 설정할 수 있다.

nav {
	a{
    	padding: 2em;
        font-size: 2em;
        &.blue{background-color: #00f;}
	}
}

3.2 위에서 &는 상위부모 (여기서는 a)를 치환한다고 보면되는데 자세한 설명은 REF참고. 

 

Posted by yongary
,

spring test에서 간단히 새로운 DB로 연결하는 방법.

 

@AutoConfigureMockMvc

class MyTest{
	
    @Container
    static MongoDbContainer mongoDBContainer = new MongoDBContainer("mongo:4.4.2"); //docker Image Name
    
    @DynamicPropertySource
    static void setProperties(DynamicPropertyRegistry dymDynamicPropertyRegistry) {
    	dymDynamicPropertyRegistry.add("spring.data.mongodb.uri", mongoDBContainer::getReplicaSetUrl);
    }

		

}
Posted by yongary
,

마커 I/F, String(B...)

java core 2023. 2. 15. 21:23

대표적으로 Serializable, Clonable 등과 같이 실제로는 완전히 비어있는  마크전용 interface를 Mark interface라고 부른다.

목적은 type 체크를 위해서라고 보면 좋을것 같다.    Mark Annotation이라는 것도 있는데 -> REF

 

String <<< StringBuffer < StringBuilder 

StringBuffer와 StringBuilder의 차이는 synchronized 함수지원해서 Thread Safe인지,  아닌지 차이이다.  StringBuilder가 synchronized가 아닌만큼 더 빠르다.   Java 1.5부터는 간단한 String concat은  컴파일시에 StringBuilder로 대체해준다.   REF

 

 StringBuilder sb = new StringBuilder();
 sb.append("문자열 ").append("연결");
 String st = sb.toString();
Posted by yongary
,

좀 오래된 기술이고 요즘 잘 쓰진 않지만, 복습용으로 기록!

 

 

rmi (remote procedure call)의 layer구조:

rmi는 Object의 Serialize를 기반으로 이루어지므로,

client에서 refrerence해서 사용하는 object가 다 사용되면, server에서 client의 Object를 gc(garbage collection)하게 되는데 이를 분산GC = DGC라고 부른다.

 

 

Applet:  flash를 거쳐 html5 canvas등으로 대체되면서 잘 안쓰고 있는 것으로 보이지만 처음 나올 당시에는 획기적인 기술이었음.
=> Life cycle은   init -> start -> paint(g) -> stop -> destroy로 이루어져 이후 많은 플랫폼들의 기초가 되었다고 생각된다.
 stop과 start는 브라우저가 최소화, 최대화 될때마다 발생한다. 

Posted by yongary
,

aggregation중에 필드별  계산이 필요할 경우,  .andExpression을 통해 계산된 결과를 바로 받을 수 있고 이후에 조건/group도 가능핟.

// [select column]
ProjectionOperation projection = Aggregation.project()
        .and("gongsunGroup").as("gongsunGroup")
        .and("farmerNo").as("farmerNo")
        .and("pummokName").as("pummokName")
        .and("pumjongCode").as("pumjongCode")
        .and("rawReceivingDay").as("rawReceivingDay")
        .and("pboxCount").as("pboxCount")
        .andExpression("divide(floor(multiply(weight, 100)),100)").as("weight")
        ;

 

.andExpression과 비슷하지만 if 조건을 걸고 싶을 경우 (oracle에서 code였던가?)
.

ConditionalOperators 와
project에  .applyCondition(cond, field("nbE"))

을 사용하면 된다.  링크: https://yongary.tistory.com/420?category=539865 

Posted by yongary
,

ssh 터널링

network개발 2022. 9. 6. 16:07

1. 220서버에 들어간 후  100번서버를 localhost:30000으로 매핑. 

ssh -p 33331 ubuntu@220.83.x.x -L 30000:192.168.30.100:30000 

==> ssh -L 8080:원격서버주소:80 중간서버주소
의미:  중간서버에 접속해서  중간서버가 접속가능한 원격서버:80로 접속하는데,   이걸 localhost:8080으로 사용한다는 의미. 
(그외: -L 파라미터는 로컬 포트 포워딩 이외에도 다른 유형의 포트 포워딩을 설정하는 데에도 사용될 수 있습니다. -R 파라미터는 원격 포트 포워딩(remote port forwarding)을 설정하는 데에 사용되며, -D 파라미터는 다이나믹 포트 포워딩(dynamic port forwarding 또는 SOCKS 프록시)을 설정하는 데에 사용됩니다.)


 

2.특정서버의 27017포트를 현서버의 57017로 터널링.


ssh  (-i 등등) -L 57017:localhost:27017 -N centos@private서버.IP

 

3:

ssh -i ~/.ssh/my.pem -t -t -L 57017:localhost:57017 centos@54.xx.xx.xx ssh -i my.pem -L 57017:localhost:27017 -N centos@VPCIP

Posted by yongary
,

 

[1.기본설치 - mongoDB 5.0 기준]

 

MongoDB 저장소 추가하기

1. MongoDB는 CentOS의 기본 저장소에 포함되어 있지 않으므로, 별도의 저장소를 추가해야 합니다. 다음 명령어를 터미널에서 실행하여 MongoDB 저장소를 추가합니다

 

$ sudo vi /etc/yum.repos.d/mongodb-org-5.0.repo

아래내용 입력 저장.

[mongodb-org-5.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/5.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-5.0.asc
 
2. 그 다음에 진짜 설치.
- $sudo yum install mongo-org

 

3. 설치 완료후 설정 수정.

- /etc/mongod.conf 에  bindIp를 0.0.0.0 으로 수정.

 

4. 시작 

- $sudo systemctl start mongod 
=> (start를  status로 고치거나, restart로 고치면, 상태조회, 재시작 가능.)

 

 

 

 

[2. replicaSet 설정 법]

https://docs.mongodb.com/manual/tutorial/deploy-replica-set/

  - /etc/mongod.conf 에 replication 추가 필요. [기본 3서버 설정 기준, =>  2서버 1가상 arbiter설정은 아래 참조]
replication:
   replSetName: "rs0" 

 

  • (sudo) service mongod start
  • 3대가 다 시작되면 그 중에 한대에 mongo 로 접속해서 아래명령 실행필요,
arbiter없을 경우:
  rs.initiate({
   _id : "rs0",
   members: [
      { _id: 0, host: "172.31.47.103:27017" },
      { _id: 1, host: "172.31.46.185:27017" },
      { _id: 2, host: "172.31.43.168:27017" }
   ]
})

arbiter있을 경우:
  rs.initiate({
   _id : "rs0",
   members: [
      { _id: 0, host: "172.31.47.103:27017" },
      { _id: 1, host: "172.31.46.185:27017" }
   ]
})

rs.conf() 및 rs.status()로 확인가능.

 

[2서버 1 아비터 설정시]

arbiter 세팅시에는, member2개로 rs.initiate하고 rs.addArb(“host:port”)를 수행.

https://thomassileo.name/blog/2012/03/08/how-to-mongodb-replica-sets/

그전에 arbiter 기동은 https://docs.mongodb.com/manual/tutorial/add-replica-set-arbiter/ 

1. $sudo mkdir -p /var/lib/mongodb/arb

2. $sudo mongod --dbpath /var/lib/mongodb/arb --replSet rs0 --bind_ip 0.0.0.0

 

 

priority변경 은: PRIMARY서버에 붙은 후

cfg = rs.conf()
cfg.members[0].priority = 0.5
cfg.members[1].priority = 1.0
cfg.members[2].priority = 0.5
rs.reconfig(cfg) 

 

Posted by yongary
,

1. aggregation시 조건부 sum을 하는 방법입니다.

https://stackoverflow.com/questions/41218321/grouping-and-sum-with-conditions

 

ConditionalOperators.Cond cond = when(Criteria.where("status").is("PRESENT")).then(1)
                .otherwise(when(Criteria.where("status").is("ABSENT")).then(2)
                .otherwise(100));
                
//ond operatorNbS = ConditionalOperators.when("scst").thenValueOf(1).otherwise(0);

Aggregation agg = newAggregation(
    match(Criteria.where("bid").is("build_1481711758"),
    project("bid") 
        .and("scst")                            
        .applyCondition(cond, field("nbE"))

 

2. aggregation시 substring을 이용한 조건부 sum을 하는 방법입니다.

https://recordsoflife.tistory.com/463

Posted by yongary
,

WebGL은 OpenGL기반으로 만들어진 javascript용 라이브러리이다.

react에서 활용가능한 webGL 라이브러리가 여러가지 있으나 three.js가 괜찮아 보인다.

지원 브라우저에 주의하여야 한다.

 

저장포맷으로는 JSON기반인 glTF 를 많이 사용한다. 


(webGL 관련 예제)
https://code-masterjung.tistory.com/m/101?category=928099 

 

React로 Threejs 예제 따라 구현하기

 css를 공부하다 보니 자연스레 WebGL에 관심이 생겨 기본 개념을 익힐 겸 공식 문서를 따라 만들어 보았다(openGL은 일단 조금 나중에 다시 보는 걸로..). 사실 문서가 너무 잘 돼있어 예제를 단순히

code-masterjung.tistory.com

 

Posted by yongary
,

//summaryStatistics 를 이용한 통계방식 적용.
DoubleSummaryStatistics tpStat = list.stream().mapToDouble( log -> log.getTemp()).summaryStatistics();

 

이렇게 하면 다음과 같은 값들을 한번에 구할 수 있다. 사용법은 tpStat.getCount(), getSum() 등등

private long count;
private double sum;
private double min;
private double max;

Posted by yongary
,

기본적인 서버구성이 끝났다면.. (여기서는 2대의 서버에, route53을 통해 도메인 하나 공급을 가정)
  - 기본서버설정(jdk설정) : www.liquidweb.com/kb/install-java-8-on-centos-7/ 

  - ulimit설정    : https://www.baluna.ro/increasing-file-descriptors-and-open-files-limit-in-centos-7/

  - 혹시 efs연동시에는 : docs.aws.amazon.com/efs/latest/ug/efs-onpremises.html 참조. 

  - 타임존 설정: $sudo timedatectl set-timezone Asia/Seoul

  - 로케일 설정: ma.ttias.be/warning-setlocale-lc_ctype-cannot-change-locale-utf-8-no-such-file-or-directory/ 

 

(zooKeeper서버 설정시에는 /root/zookeeper/conf/zoo.cfg 에 자기IP만 0.0.0.0 다른 2서버  IP기재 + /var/zookeeper/myid 를 각각 1,2,3으로 설정)

 

1.    AWS의 ACM을 통해 인증서를 발급 받는다.              (참고: jojoldu.tistory.com/434

 

AWS의 Certificate Manager 로 SSL 인증서 발급 받기

보통 서비스가 소규모라면 1대의 서버에 Nginx를 설치하고 Let's Encrypt 를 설치해서 SSL을 등록합니다. 다만 이럴 경우 트래픽이 늘어 로드밸런서 + 여러 서버 구성으로 확장하기가 쉽지 않습니다.

jojoldu.tistory.com

  - 진행 중, [Route53에서 레코드 생성]버튼이 안나올 경우. 

      =>1방법(잘안됨) :  도메인 구매한 사이트의, 도메인 구성에 가서 CNAME 레코드를 추가한다.
         CNAME :  _990122b262bc3ecxxxx.acm-domainname.com 형태로 key와 value를 추가한다. 
             (hostname은 _990122b262bc3ecxxxx 까지만, . TTL은 3600정도..)
      => 2방법: route53으로 직접가서 호스팅영역(mydomain.com)을 먼저추가하고, AWS에 알려주는 4개
              (예: ns-620.awsdns-1.net.
ns-222.awsdns-31.com.ns-333.awsdns-26.co.uk. ns-444.awsdns-50.org.)
          를 도메인 구매한 사이트의, 도메인 구성에 가서 네임서버 1차,2차,3차,4차 로 설정한다.
           ==> 2방법 이후에 [Route53에서 레코드 생성]버튼이 보이므로, 누르면 된다.

       
     (30분 가량 대기하면 인증서 발급이 된다)

2. 그 후, 로드밸런서를 생성한다.

   로드밸런서 설정에서 타겟그룹을 구성하고, 서버2대를 추가.

 

   로드밸런서의 인증서 선택은 1에서 생성한 인증서를 선택한다. 
   보안그룹은 하나 만들어서 넣거나, 미리 만들어 둔 후 고르면 되고(후자 권장)

 

   라우팅 구성, 대상그룹 선택에서 앞서만든 타겟그룹을 추가하면 된다.  프로토콜은 HTTP로 된다. 

 

3. 로드밸런서 stickiness

   - 로드밸런서로 서버 2대에 부하를 분산할 경우,  접속자가 동일한 서버로 계속 접속되는 게 세션관리나 log측면에서 편하다.

  - 이 기능을 stickiness라고 하는데, AWS에서는 stickiness 세팅을 로드밸런서에 하지 않고,  Target Group에서 한다.


  아래 그림과 같이 Attribute에서 stickiness와 stickiness duration을 세팅하면 된다.    

   

 

4. 마지막으로, route53에 가서 A.레코드 세트를 추가하면서, Alias사용을 선택하면 로드밸런서를 선택할 수 있다.
  이름은 안넣고 하나생성, www 넣고 하나생성 .. 이렇게 A레코드 2개 세트 권장.

Posted by yongary
,

CSRF, JWT 토큰

IT 2020. 7. 29. 15:09

csrf 는 웹서비스에서 cross-site-request-forgery를 막기위해

백엔드에서 토큰을 발행하고 프론트엔드에서 이를 사용하여 최종적으로는 유효한 요청인지를 확인하는 방식.

 

 

JWT토큰은 인증에 사용되는 방식으로서 REF

OAuth와 연동해서 사용할 수도 있고 독립적으로 사용할 수도 있다.

 

 OAuth1과 OAuth2의 가장 큰 차이는 OAuth2의 경우 refresh 토큰이 가능. 

 

 

 

JWT를 구현하면서 마주치게 되는 고민들

최근 모바일, 웹 등 다양한 환경에서 서버와 통신하면서 많은 사람들이 JWT 토큰 인증 방식을 추천합니다. 이 포스팅에서는 JWT를 이해하고 구현하면서 마주치게 되는 고민들에 대해 정리해보려 �

swalloow.github.io

 

Posted by yongary
,

spring boot2에서부터는  controller에서 @Async에서도

completableFuture를 리턴할 수 있다..

( 그 전에도 Async와 EnableAsync는 있었는데 completableFuture를 리턴하지는 못한것 같은데, 확인 중)

 

<사전지식>

1. Future(Java5 에 등장) 와 Observable간에 전환.  (마찬가지로 CompleatbleFuture와  Single간에 전환도 유사)

Observable<String> source = Observable.fromFuture(future);

source.subscribe(System.out::println);

 

2. Future vs CompletableFuture (Java8에 등장)  : ref
    CompletableFuture.complete() 함수를 호출해  Future를 수동으로 종료할 수 있음. 

    그 외 runAysnc, supplyAsync, thenApply, thenAccept, thenRun 등 함수들이 제공됨.

  

 


출처: https://12bme.tistory.com/570 [길은 가면, 뒤에 있다.]

 

[RxJava] RxJava 프로그래밍(1) - 리액티브 프로그래밍

서버 다수와 통신하게 되면 API 호출 각각에 콜백을 추가하게 된다. 콜백이 늘어나면 애플리케이션의 복잡성도 증가(callback hell)하게 된다. RxJava는 자바로 리액티브 프로그래밍을 할 수 있는 라이

12bme.tistory.com

https://12bme.tistory.com/570 

 

 

 

참고: https://howtodoinjava.com/spring-boot2/rest/enableasync-async-controller/#:~:text=1.-,Spring%20%40Async%20rest%20controller,application%20classes%20for%20asynchronous%20behavior.&text=The%20%40Async%20annotated%20methods%20can,result%20of%20an%20asynchronous%20computation.

 

Spring @Async rest controller example - Spring @EnableAsync

Spring @Async non blocking rest controller example. Learn to use spring async behavior with @EnableAsync annotation. Spring async completablefuture example.

howtodoinjava.com

 

Posted by yongary
,

Test Code 관련

springBoot gradle 2020. 7. 13. 17:19

 

 Stub/ Mock/Fake 등을 묶어‘테스트 더블(Test Double)' 이라고 한다. (여기서 Double=대역)

 

SpringBoot에선 BDDMockito를 지원해 B(Behavior) Driven Test를 지원한다.

 

 

MockMVC 과 Mockito의 차이.

- mockito가 좀 더 general하고 더 많은 case를 지원하고, 여러가지 mock도 지원한다. (mockObject.when()  등등...)

- MockMVC는 spring 전용.  

 

Posted by yongary
,

격리수준

BACK-END 2020. 7. 11. 22:15

DB의 트랜잭션은 ACID를 보장해야 한다. (참고: https://feco.tistory.com/45

 - 원자성, 일관석, 격리성, 지속성

Atomicity: 한트랜잭션이 여러query로 이루어질 수 있는데, 한 트랜잭션의 모든 query가 성공하거나, 혹은 part of transaction이 실패하면 전체 transaction이 실패/혹은 rollback해야한다. 
Consistency: 트랜잭션후에도 DB는 항상 valid state 를 유지해야 한다.(for각종 constraint들 enabled in DB)
Isolation : 동시에 여러개의 transaction이 실행되더라도 하나씩 고립되어 순차적으로 실행되어야한다.
Durability: 트랜잭션이 commit되고 나면, 항상 available해야한다. server가 꺼졌다 켜지더라도...

 

 

이중, "I"인 Isolation(격리성의) 수준은 (참고: https://m.blog.naver.com/PostView.nhn?blogId=blueaian&logNo=220636152759&proxyReferer=https:%2F%2Fwww.google.com%2F )

 

- READ UNCOMMITED (dirty read 발생가능 + 아래들)

   : 일반적인 Database에서는 사용하지 않음

- READ COMMITED (none-repeatable read 발생가능 + 아래 )

   : Oracle 트랜잭션 격리 수준 ( OLTP에서 많이 채택 )

   : commit된 데이터에 대해 다른 세션에서 읽을 수 있음

- REPEATABLE READ  (Phantom Read발생가능)

  : Mysql 기본 격리수준

  : select 에 대해서도 MVCC 수준 유지

- SERIALIZABLE

  : 동시성이 중요한 Database에서는 사용하지 않음

 

Posted by yongary
,

점을 V(Vertex)
edge를 E라고 하면..

 

처음에 V를 쭉 더해놓고

다음부터는 BFS (혹은 DFS도 가능)

 

따라서 complexity는 O (V + E) 

 

https://www.geeksforgeeks.org/detect-cycle-undirected-graph/

cycle find 코드예제:

더보기
import java.util.*;

class Graph {
    private int V;
    private LinkedList<Integer>[] adj;

    Graph(int v) {
        V = v;
        adj = new LinkedList[v];
        for (int i = 0; i < v; ++i)
            adj[i] = new LinkedList();
    }

    void addEdge(int v, int w) {
        adj[v].add(w);
        adj[w].add(v);
    }

    boolean isCyclicUtil(int v, boolean[] visited, int parent) {
        visited[v] = true;
        for (Integer i : adj[v]) {
            if (!visited[i]) {
                if (isCyclicUtil(i, visited, v))
                    return true;
            } else if (i != parent) {
                return true;
            }
        }
        return false;
    }

    boolean isCyclic() {
        boolean[] visited = new boolean[V];
        for (int i = 0; i < V; ++i)
            if (!visited[i])
                if (isCyclicUtil(i, visited, -1))
                    return true;

        return false;
    }
}

public class CycleDetectionExample {
    public static void main(String[] args) {
        Graph g1 = new Graph(5);
        g1.addEdge(1, 0);
        g1.addEdge(0, 2);
        g1.addEdge(2, 1);
        g1.addEdge(0, 3);
        g1.addEdge(3, 4);
        
        if (g1.isCyclic())
            System.out.println("Graph contains cycle");
        else
            System.out.println("Graph doesn't contain cycle");
    }
}

코드예제임.

 

Digikstra 알고리듬.  근접한 distance 부터 하나씩 추가하는 알고리듬.

더보기
import java.util.*;

class Node implements Comparable<Node> {
    int id;
    int distance;
    
    public Node(int id, int distance) {
        this.id = id;
        this.distance = distance;
    }
    
    @Override
    public int compareTo(Node other) {
        return Integer.compare(this.distance, other.distance);
    }
}

public class DijkstraAlgorithmWithClass {
    public static void dijkstra(int[][] graph, int start) {
        int n = graph.length;
        int[] distance = new int[n];
        Arrays.fill(distance, Integer.MAX_VALUE);
        distance[start] = 0;
        
        PriorityQueue<Node> pq = new PriorityQueue<>();
        pq.offer(new Node(start, 0));
        
        while (!pq.isEmpty()) {
            Node curr = pq.poll();
            int node = curr.id;
            int dist = curr.distance;
            
            if (dist > distance[node]) continue;
            
            for (int neighbor = 0; neighbor < n; neighbor++) {
                int weight = graph[node][neighbor];
                if (weight > 0 && distance[node] + weight < distance[neighbor]) {
                    distance[neighbor] = distance[node] + weight;
                    pq.offer(new Node(neighbor, distance[neighbor]));
                }
            }
        }
        
        // 출력: 각 노드까지의 최단 경로 길이
        System.out.println("Node\tDistance");
        for (int i = 0; i < n; i++) {
            System.out.println(i + "\t" + distance[i]);
        }
    }
    
    public static void main(String[] args) {
        int[][] graph = {
            {0, 4, 0, 0, 0, 0, 0, 8, 0},
            {4, 0, 8, 0, 0, 0, 0, 11, 0},
            // 나머지 그래프 데이터도 입력
        };
        
        dijkstra(graph, 0);
    }
}
Posted by yongary
,

간단한 @StreamListener  annotation만으로 stream 통신을 할 수 있으므로, MSA에서 유리하다.

 

https://coding-start.tistory.com/139

 

Kafka - Spring cloud stream kafka(스프링 클라우드 스트림 카프카)

Kafka - Spring cloud stream kafka(스프링 클라우드 스트림 카프카) 이전 포스팅까지는 카프카의 아키텍쳐, 클러스터 구성방법, 자바로 이용하는 프로듀서,컨슈머 등의 글을 작성하였다. 이번 포스팅은 �

coding-start.tistory.com

 

그 외에
 SpringCloud Eureka : MSA환경에서 서버들을 registry 해놓고, 로드밸런서와 같은 역할 가능.

 

 springcloud zuul : MSA환경에서 G/W를 이용해 token 체크등을 한 곳에서  모아서 할 수 있다.

 

 

 

Posted by yongary
,

Arrays (feat Stream)

java8~ 2020. 7. 4. 20:41

1. Arrays.stream     

 

int[] arr = new int[] { 3, 5, 8} 

Arrays.stream( arr).filter(x -> x <=5).sum();

 

==> 근데 딱 한군데, arr -> List로 바꿀때는 잘 안됨.

List<Integer> list = IntStream.of(arr).boxed().collect(Collectors.toList())

           (boxed()가 primitive array를 단일 element로 잘라 줌)

 

참고: Stream<String> st = Stream.of("A", "B","C"); 등  다양한 Stream생성 방식:  https://codechacha.com/ko/stream-creation/

 

2. Arrays.sort 

int[][] arr = new int[][]{ {1,2,3} {4,5,2}}

Arrays.sort(arr,  (a, b) -> (a[2] - b[2]) ) ;   //Comparator를 functional로 바로 넣음..

3. Arrays.binSearch (arr, target)

  -> 찾으면 idx리턴, 못 찾으면 들어갈 자리  -idx-1 리턴..  :항상 음수를 리턴하기 위해..


 

====stream 통계=====


min/max/avg 등을 한꺼번에 구할때..

DoubleSummaryStatistics stat =  arr.stream().mapToDouble(x -> x).summaryStatistics();


stat = {counnt:10.0, sum:120.0, min:1.0, aveerage:10.11, max:19.0}

 

 

Posted by yongary
,

 

기본적으로 설치해서  fabric-samples/fabcar/startFabric.sh 를 하면

 

/network.sh up createChannel -ca -s couchdb 로 실행이 된다,.

 

이 때

./organizations/peerOrganizations 를 참조하면서. (아래 3개 파일 이용)

    org1.example.com/fabric-ca-client-config.yaml*
    org1.example.com/connection-org1.json
    org1.example.com/connection-org1.yaml

 

 

노드1, 노드2를 물리적으로 분리할 경우 (https://www.slideshare.net/hlkug/201903-hyperledger-fabric)

<노드 1>
- 채널생성 (peer channel create),

- 채널Join  (peer channel join),

- Anchor Peer 업데이트 (peer channel update)

- 체인코드 설치(peer chaincode install),

- 체인코드 Instantiate(peer chaincode instantiate),

- 체인코드 Query(peer chaincode query)

<노드 2>

- 제네시스 Block Fetch (peer channel fetch 0...)

- 채널Join  (peer channel join),

- Anchor Peer 업데이트 (peer channel update) 

- 체인코드 설치(peer chaincode install),

- 체인코드 Query(peer chaincode query)

 

 

개인이 만든 fabric-starter.git 참고 (https://www.altoros.com/blog/deploying-a-multi-node-hyperledger-fabric-network-in-5-steps/ ) - 테스트 필요.

Posted by yongary
,

 

<spring 에서 fabric G/W를 이용한 컨트랙트 실행>

implementation 'org.hyperledger.fabric:fabric-gateway-java:2.0.0'  추가 후 아래소스 참조.

https://hyperledger.github.io/fabric-gateway-java/

 

 

 

<유저 생성 후 실행 example>

https://newtechstax.com/2019/11/12/integrating-fabric-blockchain-with-springboot-application/

Posted by yongary
,

CA는

- ID를 등록하고 LDAP과 연결해서 사용자 등록수행

- ECert 발행 (Enrollment Certi)

- Certi 갱신과 철회

 

CA_server와  CA_client로 구성.

<CA server>

$fabric-ca-server start -b <admin>:<adminpw>

 

<CA client>

$export FABRIC_CA_CLIENT_HOME=$HOME/fabric-ca/clients/admin 
$fabric-ca-client register --id.name admin2 --id.affiliation org1.department1 --id.attrs 'hf.Revoker=true,admin=true:ecert'

 

 

 

<참고 사이트>

https://hyperledger-fabric-ca.readthedocs.io/en/release-1.4/users-guide.html

 

Fabric CA User’s Guide — hyperledger-fabric-cadocs master documentation

This section describes how to configure the Fabric CA server to connect to PostgreSQL or MySQL databases. The default database is SQLite and the default database file is fabric-ca-server.db in the Fabric CA server’s home directory. If you don’t care about

hyperledger-fabric-ca.readthedocs.io

 

 

Posted by yongary
,

 

redis를 이용해서 httpSession을 공유하는 방식이 좀 더 많이 활용되지만,

 

이미 mongoDB를 사용하고 있다면, mongoDB를 활용한 session공유가 더 좋을 수 있다.

특히 요즘엔 HDD대신에 SSD를 많이 사용하므로  SSD기반의 mongoDB라면 redis에 가까운 속도를 낼 것으로 예상된다.

 

 

spring-boot에서 사용하려면

gradle방식의 경우 dependency를 아래와 같이 추가하고

      compile('org.springframework.session:spring-session-data-mongodb')

 

 

 

HttpSessionConfig 클래스만 만들면 된다. ( default가 30분이라서 1시간으로 바꾼 예제이다. )

@EnableMongoHttpSession(maxInactiveIntervalInSeconds = 3600) //default 1800
public class HttpSessionConfig {
    @Bean
    public JdkMongoSessionConverter jdkMongoSessionConverter() {
        return new JdkMongoSessionConverter(Duration.ofMinutes(60)); //default 30
    }
}
Posted by yongary
,

1. char -> AsciiCode
   'A'.charCodeAt()  => 65  ,    'AB'.charCodeAt(1) => 66

 

2. AsciiCode -> char
   String.fromCharCode(65) => 'A'

 

 

 

 

//Ascii를 이용한 간단한 암호화 알고리듬. 

function encrypt(str) {   //입력이 length=7자리 정도는 된다고 보면  'ABCDEFG'

    //ascii값에 (index+1)더하기.   A+1, B+2, C+3..  G+7

   let rotatedStr = '';

   for (let i = 0; i < str.length; i ++) {
          rotatedStr = rotatedStr + String.fromCharCode(str.charCodeAt(i) + ( i +1 ))
   } 
    
   //로테이션 시키고    //중간에 양념넣기
   let tempStr = '0xe0' + rotatedStr.substring(3) + 'T2n0' + rotatedStr.substring(0,3);  //(4) + 4 + (4) +[3] : DEFG + TEMP + ABC

   return tempStr;

}


function decrypt(tempStr) {  //length:11  

  //양념빼면서 로테이션 해제  //3+4로 복귀

  let rotatedStr = tempStr.substring(tempStr.length - 3) + tempStr.substring(4, tempStr.length-7 )  //뒤 + 앞. 

   

  let str = '';
  for (let i = 0; i < rotatedStr.length; i ++) {
          str = str + String.fromCharCode(rotatedStr.charCodeAt(i) - ( i +1 ));
  } 

  return str;

}

 

Posted by yongary
,

JSON Document

mongoDB, redis 2019. 12. 18. 23:52

Java class를 이용해서 mongoDB에 저장하면서 spring에서 지원하는 mongoTemplate을 쓰는게 가장 편한데,

 

가끔은 이 방법이 불편할 때가 있다.

 

Class가 Collection에 1:1 대응되지만,  Colletion에 필드가 너무 만은데

몇개만 front-End로 리턴해야 한다던지 하는 경우에 매우 불편할 수 있는데, 이럴때 좋은게 Json Document 이다.

 

주로 사용하게 되는 class는

      JSONObject, JSONArray   (net.minidev.json 패키지)

      Document  (mongoDB 저장된 record  org.bson 패키지)

이렇게 3가지 이며,

 

JSONObject <-> Document간 변환을 주로 하게된다.

 

1. Doc으로 변환 후 mongoDB에 저장시에는 

      (MongoDBConnection mongoConn). getCollection("컬렉션명").insertOne( oneDoc );      과 같이 하면 된다.

      Document doc = mongoConn.getCollection("...").find();  //or filter(new FIlter....).find()

2. Doc을 다룰 때 많이 쓰는 함수는 

    Document 생성.  doc.append

                    doc.get("fieldName") => Document가 되기도 하고 List<Document>가 되기도 하고 자동.  

 

 

기타: (JSONObject <-> Document간 변환용 함수들)

   
    public static Document jsonToDoc(JSONObject json) {
        try {
            Document doc = Document.parse(json.toString());
            return doc;
        } catch(Exception ex) {
            return null;
        }
    }

    public static ArrayList<Document> jsonArrayToDoc(JSONArray json) {
        try {
            final ArrayList<Document> result = new ArrayList<Document>();
            json.stream().map(obj -> (JSONObject)obj).forEach(item->result.add(jsonToDoc(item)));
            return result;
        } catch(Exception ex) {
            return null;
        }
    }
   public static JSONObject docToJson(Document doc) {
        JsonWriterSettings settings = JsonWriterSettings.builder()
                .int64Converter((value, writer) -> writer.writeNumber(value.toString()))
                .doubleConverter((value, writer) -> writer.writeNumber(Long.toString(Math.round(value))))
                .objectIdConverter((value, writer) -> writer.writeString(value.toHexString()))
                .build();
        return (JSONObject)JSONValue.parse(doc.toJson(settings));
    }

    public static JSONArray docToJsonArray(List<Document> docs) {
        JSONArray array = new JSONArray();
        for (Document doc : docs) {
            array.add(docToJson(doc));
        }
        return array;
    }

 

 

========  BigDecimal을 Document이용해  저장하는 경우 ============

- BigDecimal amount 몽고DB 저장 시
   document.append("amount", new Decimal128(amount)));

- BigDecimal amount 몽고DB 읽기 시
   amount = ((Decimal128) document.get("amount")).bigDecimalValue();

 

========vs. BigDecmial을  mongoTemplate을 이용해 저장하는 경우========

그냥 필드를 BigDecimal로 해 놓으면 자동으로 String처럼 변환되면서 mongoTemplate사용 가능할 것으로 예상.
안되면 https://stackoverflow.com/questions/37950296/spring-data-mongodb-bigdecimal-support참조. 

Posted by yongary
,

Kafka vs. RabbitMQ

network개발 2019. 12. 2. 19:31

둘다 속도가 엄청 좋지만,

kafka와 rabbitMQ는 큰차이점이 있다.  REF
 

1. kafka는 pull 방식, rabbit MQ는 push 방식.

2. rabbitMQ는 in Memory cluster를 많이 쓰지만, kafka는 sequential Disk I/O를 많이 쓰므로
  H/W 비용이 kafka 가 저렴하다.

 

그 외 차이점 몇가지를 표로 보면: 

 

 

Posted by yongary
,