간단한 @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
,

DFS with Stack

algorithm & type 2019. 11. 14. 21:48

BinaryTree를 DFS(depth first search)하기에는 recursion이 간편하다.

하지만 recursion 없이 stack을 이용하는 방법도 있는데, java코드로 표현하면 다음과 같다.

 

 

static void printDFS(Node node) {

        Stack<Node> stack = new Stack<>();

        Node temp = node;
        while (temp != null || !stack.isEmpty()) {

            //(THIS + Left)푸쉬 => left,this,right 출력.
            while (temp != null) {
                //this push
                stack.push(temp);
                //left traverse
                temp = temp.left;
            }

            //start print
            temp = stack.pop();
            print(temp); /////////////////////////////////////

            //right point : goto TOP
            temp = temp.right;
        }
    }
Posted by yongary
,