<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by 달빛방랑 on Medium]]></title>
        <description><![CDATA[Stories by 달빛방랑 on Medium]]></description>
        <link>https://medium.com/@odysseymoon?source=rss-2b38b424d093------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Rv5AWT-SO-VyiynHTam--A.jpeg</url>
            <title>Stories by 달빛방랑 on Medium</title>
            <link>https://medium.com/@odysseymoon?source=rss-2b38b424d093------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 11:55:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@odysseymoon/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Spring Cloud Stream with RabbitMQ]]></title>
            <link>https://medium.com/@odysseymoon/spring-cloud-stream-with-rabbitmq-c273ed9a79b?source=rss-2b38b424d093------2</link>
            <guid isPermaLink="false">https://medium.com/p/c273ed9a79b</guid>
            <category><![CDATA[spring-cloud-stream]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <dc:creator><![CDATA[달빛방랑]]></dc:creator>
            <pubDate>Wed, 27 May 2020 10:34:07 GMT</pubDate>
            <atom:updated>2020-05-27T10:34:07.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/373/0*nHsMfIYBldGLQVO7.png" /><figcaption><a href="https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.4.RELEASE/reference/html/spring-cloud-stream.html#spring-cloud-stream-overview-application-model">https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.4.RELEASE/reference/html/spring-cloud-stream.html#spring-cloud-stream-overview-application-model</a></figcaption></figure><h3>Spring Cloud Stream</h3><p>Spring Cloud Stream 프로젝트는 Message 기반 마이크로 서비스 어플리케이션을 만들기위한 Framework 로 메시징 시스템과 연동하여 확장성 높은 이벤트 기반 마이크로 서비스를 구축 가능하게 해줍니다.<br>높은 추상화를 통해 어떤 인프라인지를 알 필요 없이 어플리케이션 설정과 간단한 구현 만으로 메시징 시스템을 구현할 수 있습니다.</p><h4>Main Concept</h4><p>Programming 을 통한 구현을 위해서는 아래 간단한 컨셉을 일단 알고 가야 합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*oJ8MG7j9AUjqgpNk.png" /></figure><p><strong><em>Destination Binder</em></strong> : 외부 메시징 시스템 (Kafka 또는 RabbitMQ)과의 연동을 책임지는 컴포넌트로 유저가 직접 구현시 책임져야 할 많은 boiler-plate한 코드들을 제공해 줍니다.</p><p><strong><em>binding</em></strong> : 외부 메시징 시스템과 어플리케이션에서 제작된 Producer Consumer 사이의 브릿지로서 binding name 을 통해 property에서 설정하여 사용할 수 있습니다.</p><p><strong><em>Message</em></strong> : Destination Binder 와 통신하기 위한 정규화 데이터 구조로 POJO 객체를 그대로 사용할 수 있습니다.</p><p>위 그림에서 보이는 것처럼 외부 메시징 시스템과 연동 및 설정은 Spring Property를 통해 추상화되고 사용자는 Application 주요 로직만 신경 쓸 수 있도록 높은 추상화를 제공합니다.</p><h3>RabbitMQ</h3><p>각각의 특성과 용도가 달라 어느 메시징 시스템을 사용해도 상관없으며, 본문에서는 Rabbit MQ를 사용한 P2P 메시지와 Pub-Sub 구조의 메시징 시스템을 만들어 보겠습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*_YMwApB31Fj4xuBY.png" /><figcaption>RabbitMQ Binder</figcaption></figure><p>RabbitMQ Binder는 Topic을 기반한 Exchange Output(Producer)과 Queue를 통한 Input(Consumer)을 제공하고 있습니다.</p><h4>docker 설정</h4><p>테스트를 위해 아래와 같이 docker-compose를 통해 RabbitMQ를 설정합니다.</p><ul><li>docker-compose.yaml</li></ul><pre><strong>version: &#39;3&#39;<br>services:<br>  rabbitmq:<br>    image: &#39;rabbitmq:3-management-alpine&#39;<br>    container_name: </strong>rabbitmq-stream<br>    <strong>ports:<br>      - &#39;5672:5672&#39;<br>      - &#39;15672:15672&#39;<br>    environment:<br>      RABBITMQ_ERLANG_COOKIE: &quot;RabbitMQ-My-Cookies&quot;<br>      RABBITMQ_DEFAULT_USER: &quot;admin&quot;<br>      RABBITMQ_DEFAULT_PASS: &quot;admin&quot;</strong></pre><p>docker-compose up 또는 docker-compose up -d 를 명령어를 통해 docker 를 실행시키고, 브라우저를 통해 http://localhost:15672 로 접속해 RabbitMQ상태를 모니터링 합니다.</p><h3>Annotation-based vs Functional</h3><p>Spring Cloud Stream 3.0부터는 spring-cloud-stream-reactive 가 합쳐지면서 Function 을 기반으로 한 Routing Function , Multiple bindings with Functions , Functions with multiple inputs/outputs , Native support for reactive programming 등이 지원되면서 Annotation 을 활용한 방식은 Legacy 방식으로 취급되고 있습니다. 하지만 꼭 Functional 방식을 사용할 필요는 없으며 필요에 따라 Spring Integration 등을 활용하는 다양한 방식을 모두 지원하고 있습니다.</p><p>여기서는 Annotation-based 방식과 Functional 방식 두 가지 예를 모두 살펴보겠습니다.</p><h4>Configuration</h4><ul><li>pom.xml</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81ba51f9d8b3d29c3fdfa0dd40c544d8/href">https://medium.com/media/81ba51f9d8b3d29c3fdfa0dd40c544d8/href</a></iframe><p>Spring Boot 관련 디펜던시와 함께 spring-cloud-starter-stream-rabbit 을 통해 연관 디펜던시를 모두 추가 할 수 있습니다.</p><h3>Annotation-based</h3><p>기존의 방식을 통한 Spring Cloud Stream 을 사용할 때 Spring Integration을 사용한 다양한 방식 ( @MessagingGateway 와 IntegrationFlow 등) 들을 활용할 수 있습니다. 여기에서는 StreamBridge 를 사용한 Publisher와 @StreamListener 를 사용한 Consumer를 알아보도록 하겠습니다.</p><h4>Publisher</h4><ul><li>application.yaml</li></ul><pre><strong>spring:<br>  profiles: </strong>local<br>  <strong>cloud:<br>    stream:<br>      bindings:<br>        direct:<br>          binder: </strong>rabbit<br>          <strong>destination: </strong>p2p-topic<br>        <strong>broadcast:<br>          binder: </strong>rabbit<br>          <strong>destination: </strong>pubsub-topic<br>  <strong>rabbitmq:<br>    addresses: </strong>localhost<br>    <strong>username: </strong>admin<br>    <strong>password: </strong>admin</pre><p>spring.rabbitmq 를 통해 RabbitMQ 관련 접속 정보를 설정해 줍니다. <br> Spring Cloud Stream 에서는 앞서 언급한 Binding Name 을 통해 Stream IN/OUT을 설정할 수 있습니다. <br>Legacy 방식에서는 spring.cloud.bindings.&lt;Binding Name&gt;.destination 을 통해 Binding Name 에 연관된 RabbitMQ Topic Exchange 를 설정해 줄 수 있습니다. 위 예시에서는 direct 와 broadcast 의 두 개의 Binding을 설정하였습니다.</p><ul><li>Source</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/471501f98e6b495b01328f1371e328e8/href">https://medium.com/media/471501f98e6b495b01328f1371e328e8/href</a></iframe><p>ProducerChannel 을 통해 Binding Interface 를 정의하고 @EnableBinding 을 통해 적용해주면 application.yaml 을 통해 정의한 Binding Name 들과 연결할 수 있습니다.</p><p>위 예제에서는 REST 호출을 통해 외부에서 부터 시작된 데이터를 Stream 으로 전달하기 위해서 StreamBridge 를 활용하였습니다. <a href="https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.4.RELEASE/reference/html/spring-cloud-stream.html#_sending_arbitrary_data_to_an_output_e_g_foreign_event_driven_sources">참고</a></p><p>StreamBridge.send() 를 통해 ProducerChannel 에 정의된 Binding Name 을 찾고 해당하는 spring.cloud.stream.bindings 의 Topic으로 메시지를 전달할 수 있습니다. (기본 메시지 타입은 application/json 입니다.) <a href="https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.4.RELEASE/reference/html/spring-cloud-stream.html#_common_binding_properties">참고</a></p><blockquote>아직 현재까지는 direct 와 broadcast 가 설정에 차이가 없습니다.</blockquote><h4>Consumer</h4><ul><li>application.yaml</li></ul><pre><strong>spring:<br>  profiles: </strong>local<br>  <strong>cloud:<br>    stream:<br>      bindings:<br>        direct:<br>          binder: </strong>rabbit<br>          <strong>destination: </strong>p2p-topic<br>          <strong>group: </strong>p2p-group<br>          <strong>durableSubscription: </strong>true<br>        <strong>broadcast:<br>          binder: </strong>rabbit<br>          <strong>destination: </strong>pubsub-topic<br>  <strong>rabbitmq:<br>    addresses: </strong>localhost<br>    <strong>username: </strong>admin<br>    <strong>password: </strong>admin</pre><p>Consumer에서도 동일하게 RabbitMQ 관련 설정을 정의해주고 Spring Cloud Stream 관련 대상 Topic도 정의해 줍니다. Topic 메시지를 한 Consumer만 처리할 수 있도록 group 을 정의해 주고 Consumer가 하나도 없을 경우 메시지를 저장하고 Consumer 접속 시 저장된 메시지를 전달하도록 durableSubscription 을 true 로 설정해 줍니다.</p><ul><li>Source</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/137535bb14ec64df3b295b7715449842/href">https://medium.com/media/137535bb14ec64df3b295b7715449842/href</a></iframe><p>ConsumerChannel 을 통하여 Binding Interface 를 정의합니다. @Input 을 통해 Consumer를 정의할 때는 @Output 과는 달리 MessageChannel 의 하위 인터페이스인 SubscribableChannel 을 사용해야 합니다.</p><p>메시지를 처리할 때에는 @StreamListener 를 통해 Binding된 메시지를 바로 처리 할 수 있습니다.</p><p>만약 메시지를 처리해서 다른 Stream으로 바로 전달하고 싶다면 @SendTo 를 함께 사용하여 Stream 으로 바로 Publish할 수 있습니다.</p><p>Publisher 와 Consumer 두 어플리케이션을 실행한 상태로 curl 과 같은 도구를 이용하여 아래와 같이 호출해 보면 Publisher -&gt; RabbitMQ -&gt; Consumer 로 메시지가 전달되는 것을 확인 할 수 있습니다.</p><pre>curl -X GET &#39;<a href="http://localhost:8080/api/direct/hi12&#39;">http://localhost:8080/api/direct/hi&#39;</a><br>curl -X GET &#39;<a href="http://localhost:8080/api/broadcast/hiAll12&#39;">http://localhost:8080/api/broadcast/hiAll&#39;</a></pre><h3>Functional way</h3><p>Functional 방식에서는 Binding Name 이 중요합니다. 어플리케이션에서 정의된 Functional Interface 명을 활용하여 다음과 같은 규칙을 통해 Input/Output 정의할 수 있습니다.</p><p><strong><em>Input </em></strong>: &lt;function name&gt; + -in- + &lt;index&gt; <br><strong><em>Output</em></strong> : &lt;function name&gt; + -out- + &lt;index&gt;</p><p>&lt;index&gt; 값은 input/output Binding 순번으로 <a href="https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.4.RELEASE/reference/html/spring-cloud-stream.html#_functions_with_multiple_input_and_output_arguments">Multiple Input/Output</a> 이 아닐 경우 0 으로 설정합니다.</p><p>Functional 방식에서는 Binding Interface 를 정의할 필요 없이 @Bean 으로 등록된 Supplier&lt;T&gt; , Function&lt;T, R&gt; , Consumer&lt;T&gt; 를 인지하여 Function Name 과 Property에 설정된 binding Name 을 자동으로 연결해 줍니다.</p><h4>Publisher</h4><ul><li>application.yaml</li></ul><pre><strong>spring:<br>  profiles: </strong>local<br>  <strong>cloud:<br>    function:<br>      definition: </strong>direct;broadcast<br>    <strong>stream:<br>      bindings:<br>        direct-out-0:<br>          destination: </strong>p2p-topic<br>        <strong>broadcast-out-0:<br>          destination: </strong>pubsub-topic<br>  <strong>rabbitmq:<br>    addresses: </strong>localhost<br>    <strong>username: </strong>admin<br>    <strong>password: </strong>admin</pre><p>direct 와 broadcast 두 개의 Function 을 정의 했을 때 외부 Stream 으로 메시지를 발행해야 하기 때문에 direct-out-0 과 같은 형태로 Binding Name 을 정의하게 됩니다. 그리고 정의된 Function 이 두 개 이상일 때에는 spring.cloud.function.definition 을 통해 구분자 ; 와 함께 정의된 Function Name 을 기술해 줘야 합니다.</p><ul><li>Source</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73f98e5b72974f8b15ba2c16c0b9faf5/href">https://medium.com/media/73f98e5b72974f8b15ba2c16c0b9faf5/href</a></iframe><p>앞서 설정한 Binding Name 과 정의된 Supplier 를 통해 Stream 으로 메시지를 보낼 수 있으며, 위 예에서는 REST 호출을 통해 메시지를 전달하기 위해 <a href="https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.4.RELEASE/reference/html/spring-cloud-stream.html#_using_reactor_api">EmitterProcessor</a> 를 활용해야 합니다. Binding Interface 없이 아주 간단하게 구현 가능한 것을 확인할 수 있습니다.</p><h4>Consumer</h4><ul><li>application.yaml</li></ul><pre><strong>spring:<br>  profiles: </strong>local<br>  <strong>cloud:<br>    function:<br>      definition: </strong>direct;broadcast<br>    <strong>stream:<br>      bindings:<br>        direct-in-0:<br>          binder: </strong>rabbit<br>          <strong>destination: </strong>p2p-topic<br>          <strong>group: </strong>p2p-group<br>          <strong>durableSubscription: </strong>true<br>        <strong>broadcast-in-0:<br>          destination: </strong>pubsub-topic<br>  <strong>rabbitmq:<br>    addresses: </strong>localhost<br>    <strong>username: </strong>admin<br>    <strong>password: </strong>admin</pre><p>Binding Name 을 제외하고는 Annotation-based 방식과 동일한 것을 확인할 수 있습니다.</p><ul><li>Source</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/718d2f8bbf43f043c76862c53f7c22f4/href">https://medium.com/media/718d2f8bbf43f043c76862c53f7c22f4/href</a></iframe><p>@Bean 으로 등록된 Functional Interface 를 통해 간단히 메시지를 처리하는 것을 볼 수 있습니다. 다만 Reactive Consumer 는 조금 <a href="https://cloud.spring.io/spring-cloud-static/spring-cloud-stream/3.0.4.RELEASE/reference/html/spring-cloud-stream.html#_consumer_reactive">특별</a>합니다. Consumer 가 void 를 리턴하기 때문에 subscribe 를 할 수가 없어서 Consumer&lt;Flux&lt;?&gt;&gt; 대신 Function&lt;Flux&lt;?&gt;, Mono&lt;Void&gt;&gt; 를 사용하고, then() 을 통해 리턴합니다.</p><p>Spring Cloud Stream 을 활용하면 아주 간단한 구현 만으로도 메시지 기반 마이크로 서비스 구축이 가능하며, <a href="https://spring.io/projects/spring-cloud-stream-applications">Spring Cloud Stream Applications</a> 와 <a href="https://spring.io/projects/spring-cloud-stream-app-starters">Spring Cloud Stream App Starters</a> 를 통해 설정 만으로도 서비스 구현이 가능하도록 지원하고 있습니다.</p><p>관련 소스는 아래 GitHub 링크에서 확인 가능합니다.</p><ul><li>Functional Way</li></ul><p><a href="https://github.com/Odysseymoon/spring-cloud-stream-rabbitmq">Odysseymoon/spring-cloud-stream-rabbitmq</a></p><ul><li>Annotation-based</li></ul><p><a href="https://github.com/Odysseymoon/spring-cloud-stream-rabbitmq/tree/annotation">Odysseymoon/spring-cloud-stream-rabbitmq</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c273ed9a79b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring WebClient 사용법]]></title>
            <link>https://medium.com/@odysseymoon/spring-webclient-%EC%82%AC%EC%9A%A9%EB%B2%95-5f92d295edc0?source=rss-2b38b424d093------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f92d295edc0</guid>
            <category><![CDATA[webclient]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[달빛방랑]]></dc:creator>
            <pubDate>Thu, 14 May 2020 08:09:17 GMT</pubDate>
            <atom:updated>2020-05-14T08:09:17.199Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/0*XhceqwwJ9LyB6h6R.png" /></figure><p>Spring 어플리케이션에서 HTTP 요청을 할 땐 주로 RestTemplate 을 사용했었습니다. 하지만 Spring 5.0 버전부터는 RestTemplate 은 유지 모드로 변경되고 향후 deprecated 될 예정입니다.</p><p>RestTemplate 의 대안으로 Spring 에서는 WebClient 사용을 강력히 권고하고 있으며 다음과 같은 특징을 가지고 있습니다.</p><ul><li>Non-blocking I/O</li><li>Reactive Streams back pressure</li><li>High concurrency with fewer hardware resources</li><li>Functional-style, fluent API that takes advantage of Java 8 lambdas</li><li>Synchronous and asynchronous interactions</li><li>Streaming up to or streaming down from a server</li></ul><p>Reactive 환경과 MSA를 생각하고 있다면 WebClient 사용을 적극 권장해 드리며, 기본 설정부터 Method 별 사용법까지 차근차근 알아보도록 하겠습니다.</p><h3>Configuration</h3><p>WebClient 를 사용하기 위한 가장 간단한 방법은 static factory 를 통해 WebClient 를 생성해서 사용할 수 있습니다.</p><pre>WebClient.create();<br>WebClient.create(String baseUrl);</pre><p>하지만 default 값이나 filter 또는 ConnectionTimeOut 같은 값을 지정하여 생성하기 위해서는 Builder 클래스를 통해 생성하는 것이 좋습니다.</p><p>Builer() 를 통하면</p><ul><li>모든 호출에 대한 기본 Header / Cookie 값 설정</li><li>filter 를 통한 Request/Response 처리</li><li>Http 메시지 Reader/Writer 조작</li><li>Http Client Library 설정</li></ul><p>등이 가능합니다.</p><p>Spring 여러 Bean 에서 사용하기 위해 @Configuration 을 통해 WebClient 를 선언합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5be74fbab843b71df3d9fdb7eb258c72/href">https://medium.com/media/5be74fbab843b71df3d9fdb7eb258c72/href</a></iframe><h4>MaxInMemorySize</h4><p>Spring WebFlux 에서는 어플리케이션 메모리 문제를 피하기 위해 codec 처리를 위한 in-memory buffer 값이 256KB로 기본설정 되어 있습니다. 이 제약 때문에 256KB보다 큰 HTTP 메시지를 처리하려고 하면 DataBufferLimitException 에러가 발생하게 됩니다. 이 값을 늘려주기 위해서는 ExchageStrategies.builder() 를 통해 값을 늘려줘야 합니다.</p><pre><strong>ExchangeStrategies exchangeStrategies = <br>    ExchangeStrategies<br>        .builder()<br>        .</strong>codecs<strong>(configurer </strong>-&gt; <strong>configurer.</strong>defaultCodecs<strong>()<br>                                     .</strong>maxInMemorySize<strong>(1024*1024*50))<br>        .</strong>build<strong>();</strong></pre><h4>Logging</h4><p>Debug 레벨 일 때 form Data 와 Trace 레벨 일 때 header 정보는 민감한 정보를 포함하고 있기 때문에, 기본 WebClient 설정에서는 위 정보를 로그에서 확인할 수 가 없습니다. 개발 진행 시 Request/Response 정보를 상세히 확인하기 위해서는 ExchageStrateges 와 logging level 설정을 통해 로그 확인이 가능하도록 해 주는 것이 좋습니다.</p><pre><strong>exchangeStrategies<br>    .</strong>messageWriters<strong>().</strong>stream<strong>()<br>    .</strong>filter<strong>(LoggingCodecSupport.class</strong>::isInstance<strong>)<br>    .</strong>forEach<strong>(writer </strong>-&gt; <strong>((LoggingCodecSupport)writer).</strong>setEnableLoggingRequestDetails<strong>(true));</strong></pre><p>ExchangeStrategies 를 통해 setEnableLoggingRequestDetails(boolen enable) 을 true 로 설정해 주고 application.yaml 에 개발용 로깅 레벨은 DEBUG 로 설정해 줍니다.</p><pre><strong>logging:<br>  level:<br>    org.springframework.web.reactive.function.client.ExchangeFunctions: DEBUG</strong></pre><h4>Client Filters</h4><p>Request 또는 Response 데이터에 대해 조작을 하거나 추가 작업을 하기 위해서는 WebClient.builder().filter() 메소드를 이용해야 합니다. ExchangeFilterFunction.ofRequestProcessor() 와 ExchangeFilterFunction.ofResponseProcessor() 를 통해 clientRequest 와 clientResponse 를 변경하거나 출력할 수 있습니다.</p><p>Request / Response header를 출력하는 예제를 다음과 같이 설정 할 수 있습니다.</p><pre><strong>WebClient.builder()<br>        .</strong>filter<strong>(ExchangeFilterFunction.ofRequestProcessor(<br>            clientRequest </strong>-&gt; <strong>{<br>                log.</strong>debug<strong>(&quot;Request: {} {}&quot;, clientRequest.</strong>method<strong>(), clientRequest.</strong>url<strong>());<br>                clientRequest.</strong>headers<strong>()<br>                             .</strong>forEach<strong>((name, values) </strong>-&gt; <strong>values.</strong>forEach<strong>(value </strong>-&gt; <strong>log.</strong>debug<strong>(&quot;{} : {}&quot;, name, value)));<br>                return Mono.just(clientRequest);<br>            }<br>        ))<br>        .</strong>filter<strong>(ExchangeFilterFunction.ofResponseProcessor(<br>            clientResponse </strong>-&gt; <strong>{ <br>                clientResponse.</strong>headers<strong>()<br>                              .</strong>asHttpHeaders<strong>()<br>                              .</strong>forEach<strong>((name, values) </strong>-&gt; <br><strong>values.</strong>forEach<strong>(value </strong>-&gt; <strong>log.</strong>debug<strong>(&quot;{} : {}&quot;, name, value)));<br>                return Mono.just(clientResponse);<br>            }<br>        ))</strong></pre><h4>HttpClient TimeOut</h4><p>HttpClient 를 변경하거나 ConnectionTimeOut 과 같은 설정값을 변경하려면 WebClient.builder().clientConnector() 를 통해 Reactor Netty의 HttpClient 를 직접 설정해 줘야 합니다.</p><pre><strong>WebClient<br>  .builder()<br>    .</strong>clientConnector<strong>(<br>      new ReactorClientHttpConnector(<br>        HttpClient<br>          .create()<br>            .</strong>secure<strong>(<br>              ThrowingConsumer.unchecked(<br>                sslContextSpec </strong>-&gt; <strong>sslContextSpec.</strong>sslContext<strong>(<br>                  SslContextBuilder<br>                    .forClient()<br>                 .</strong>trustManager<strong>(InsecureTrustManagerFactory.INSTANCE)<br>                    .</strong>build<strong>()<br>                )<br>              )<br>            )<br>            .</strong>tcpConfiguration<strong>(<br>              client </strong>-&gt; <strong>client.</strong>option<strong>(ChannelOption.CONNECT_TIMEOUT_MILLIS, 120_000)<br>      .</strong>doOnConnected<strong>(<br>        conn </strong>-&gt; <strong>conn.</strong>addHandlerLast<strong>(new ReadTimeoutHandler(180))<br>                    .</strong>addHandlerLast<strong>(new WriteTimeoutHandler(180))<br>                    )<br>            )<br>      )<br>    )</strong></pre><p>new ReactorClientHttpConnector() 를 통해 옵션이 추가된 새로운 HttpClient 를 설정해 줍니다.</p><p>위 예제에서는 HTTPS 인증서를 검증하지 않고 바로 접속하는 설정과, TCP 연결 시 ConnectionTimeOut , ReadTimeOut , WriteTimeOut 을 적용하는 설정을 추가하였습니다.</p><blockquote>Stream 처리에서 Exception 처리를 위한 Util인 ThrowingConsumer 는 <a href="https://github.com/Odysseymoon/spring-webflux-template/blob/master/src/main/java/moon/odyssey/webflux/utils/lambda/ThrowingConsumer.java">여기</a>를 참고하시길 바랍니다.</blockquote><h3>Usage</h3><p>WebClient 는 기존 설정값을 상속해서 사용할 수 있는 mutate() 함수를 제공하고 있습니다. mutate() 를 통해 builder() 를 다시 생성하여 추가적인 옵션을 설정하여 재사용이 가능하기 때문에 @Bean 으로 등록한 WebClient는 각 Component 에서 의존주입하여 mutate()를 통해 사용 하는 것이 좋습니다.</p><pre>WebClient a = WebClient.builder()<br>                       .baseUrl(&quot;https://some.com&quot;)<br>                       .build();<br>WebClient b = a.mutate()<br>               .defaultHeader(&quot;user-agent&quot;, &quot;WebClient&quot;)<br>               .build();<br>WebClient c = b.mutate()<br>               .defaultHeader(HttpHeaders.AUTHORIZATION, token)<br>               .build();</pre><p>위와 같이 설정 했을 경우 WebClient “c”는 “a”와 “b”에 설정된 baseUrl , user-agent 해더를 모두 가지고 있습니다.</p><p>@Bean 으로 등록된 WebClient 는 다음과 같이 사용 가능합니다.</p><pre>@Service<br>@RequiredArgsConstructor<br>@Slf4j<br>public class SomeService implements SomeInterface {<br><br>    private final WebClient webClient;</pre><pre>    public Mono&lt;SomeData&gt; getSomething() {<br>  <br>    return <strong>webClient</strong>.mutate()<br>                    .build()<br>                    .get()<br>                    .uri(&quot;/resource&quot;)<br>                    .retrieve()<br>                    .bodyToMono(SomeData.class);<br>    }<br>}</pre><h4>retrieve() vs exchange()</h4><p>HTTP 호출 결과를 가져오는 두 가지 방법으로 retrieve() 와 exchange() 가 존재합니다. retrieve 를 이용하면 바로 ResponseBody를 처리 할 수 있고, exchange 를 이용하면 세세한 컨트롤이 가능합니다. 하지만 Spring에서는 exchange 를 이용하게 되면 Response 컨텐츠에 대한 모든 처리를 직접 하면서 발생할 수 있는 memory leak 가능성 때문에 가급적 retrieve 를 사용하기를 <a href="https://docs.spring.io/spring/docs/5.3.0-SNAPSHOT/spring-framework-reference/web-reactive.html#webflux-client-exchange">권고</a>하고 있습니다.</p><ul><li>retrieve</li></ul><pre>Mono&lt;Person&gt; result = webClient.get()<br>                               .uri(&quot;/persons/{id}&quot;, id)<br>                               .accept(MediaType.APPLICATION_JSON) <br>                               .<strong>retrieve()</strong> <br>                               .bodyToMono(Person.class);</pre><ul><li>exchange</li></ul><pre>Mono&lt;Person&gt; result = webClient.get()<br>                               .uri(&quot;/persons/{id}&quot;, id)<br>                               .accept(MediaType.APPLICATION_JSON)<br>                               .<strong>exchange()</strong><br>                               .flatMap(response -&gt; <br>                                 response.bodyToMono(Person.class));</pre><h4>4xx and 5xx 처리</h4><p>HTTP 응답 코드가 4xx 또는 5xx로 내려올 경우 WebClient 에서는 WebClientResponseException이 발생하게 됩니다. 이 때 각 상태코드에 따라 임의의 처리를 하거나 Exception 을 랩핑하고 싶을 때는 onStatus() 함수를 사용하여 해결 할 수 있습니다.</p><pre><strong>webClient.</strong>mutate<strong>()<br>         .</strong>baseUrl<strong>(&quot;https://some.com&quot;)<br>         .</strong>build<strong>()<br>         .get()<br>         .</strong>uri<strong>(&quot;/resource&quot;)<br>         .</strong>accept<strong>(MediaType.APPLICATION_JSON)<br>         .</strong>retrieve<strong>()<br>         .</strong>onStatus<strong>(status </strong>-&gt; <strong>status.</strong>is4xxClientError<strong>() <br>                          || status.</strong>is5xxServerError<strong>()<br>             , clientResponse </strong>-&gt;<br>                           <strong>clientResponse.</strong>bodyToMono<strong>(String.class)<br>                           .</strong>map<strong>(body </strong>-&gt; <strong>new RuntimeException(body)))<br>         .</strong>bodyToMono<strong>(SomeData.class)</strong></pre><h4>GET</h4><p>그럼 이제부터 HTTP GET 을 호출 하는 법을 알아보겠습니다.</p><p>GET 호출은 앞서 보여진 예시에서 처럼 get() 함수를 통해 사용되며 uri() 를 통해 호출 리소스 정보를 전달해 줘야 합니다. 만약 Query 파라미터가 존재한다면 다음과 같이 변수를 추가 줄 수 있습니다.</p><pre><strong>public Mono&lt;SomeData&gt; getData(Integer id, String accessToken) {<br>    return<br>        webClient.</strong>mutate<strong>()<br>                 .</strong>baseUrl<strong>(&quot;https://some.com/api&quot;)<br>                 .</strong>build<strong>()<br>                 .get()<br>                 .</strong>uri<strong>(&quot;/resource?id={ID}&quot;, id)<br>                 .</strong>accept<strong>(MediaType.APPLICATION_JSON)<br>                 .</strong>header<strong>(HttpHeaders.AUTHORIZATION, &quot;Bearer &quot; + accessToken)<br>                 .</strong>retrieve<strong>()<br>                 .</strong>bodyToMono<strong>(SomeData.class)<br>        ;<br>}</strong></pre><p>uri() 함수를 제공하는 UriSpec 인터페이스는 아래와 같으며, Map 을 이용하거나 직접 UriBuilder 등을 통해 세세한 컨트롤도 가능합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecba8a0f71e72e41ecac1a68cf30f395/href">https://medium.com/media/ecba8a0f71e72e41ecac1a68cf30f395/href</a></iframe><h4>POST</h4><p>Body Contents를 전송할 수 있는 POST 호출 은 post() 함수를 통해 제공되며, RequestBody를 설정하기 위한 RequestBodySpec 인터페이스는 다음과 같습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d471b80ae900c8368c33bde9bd561ff8/href">https://medium.com/media/d471b80ae900c8368c33bde9bd561ff8/href</a></iframe><p>가장 많이 사용되는 form 데이터 전송과 JSON Body 데이터 전송을 간단한 예로 알아보겠습니다.</p><ul><li>form 데이터 전송</li></ul><pre><strong>webClient.</strong>mutate<strong>()<br>         .</strong>baseUrl<strong>(&quot;https://some.com/api&quot;)<br>         .</strong>build<strong>()<br>         .post()<br>         .</strong>uri<strong>(&quot;/login&quot;)<br>         .</strong>contentType<strong>(MediaType.APPLICATION_FORM_URLENCODED)<br>         .</strong>accept<strong>(MediaType.APPLICATION_JSON)<br>         .</strong>body<strong>(BodyInserters.fromFormData(&quot;id&quot;, idValue)<br>                            .</strong>with<strong>(&quot;pwd&quot;, pwdValue)<br>         )<br>         .</strong>retrieve<strong>()<br>         .</strong>bodyToMono<strong>(SomeData.class);</strong></pre><p>form 데이터를 생성하기 위해서는 BodyInserters.fromFormData() 를 이용할 수 있으며, bodyValue(MultiValueMap&lt;String, String&gt;) 을 통해서도 데이터를 전송 할 수 있습니다.</p><ul><li>JSON body 데이터 전송</li></ul><pre><strong>webClient.</strong>mutate<strong>()<br>         .</strong>baseUrl<strong>(&quot;https://some.com/api&quot;)<br>         .</strong>build<strong>()<br>         .post()<br>         .</strong>uri<strong>(&quot;/login&quot;)<br>         .</strong>contentType<strong>(MediaType.APPLICATION_JSON)<br>         .</strong>accept<strong>(MediaType.APPLICATION_JSON)<br>         .</strong>bodyValue<strong>(loginInfo)<br>         .</strong>retrieve<strong>()<br>         .</strong>bodyToMono<strong>(SomeData.class);</strong></pre><p>객체 자체를 RequestBody로 전달하기 위해서는 bodyValue(Object body) 를 사용하거나 body(Object producer, Class&lt;?&gt; elementClass) 를 통해서 사용할 수 있습니다.</p><p>또한 Mono 나 Flux 객체를 통해 RequestBody를 생성하기 위한</p><pre><strong>&lt;T, P extends Publisher&lt;T&gt;&gt; RequestHeadersSpec&lt;?&gt; body(P publisher, Class&lt;T&gt; elementClass);</strong></pre><p>함수도 존재합니다.</p><h4>PUT</h4><p>PUT 호출은 POST 호출과 유사하며 다만 put() 함수를 통해 시작되는 것 만 다릅니다.</p><pre><strong>webClient.</strong>mutate<strong>()<br>         .</strong>baseUrl<strong>(&quot;https://some.com/api&quot;)<br>         .</strong>build<strong>()<br>         .put()<br>         .</strong>uri<strong>(&quot;/resource/{ID}&quot;, id)<br>         .</strong>contentType<strong>(MediaType.APPLICATION_JSON)<br>         .</strong>accept<strong>(MediaType.APPLICATION_JSON)<br>         .</strong>bodyValue<strong>(someData)<br>         .</strong>retrieve<strong>()<br>         .</strong>bodyToMono<strong>(SomeData.class);</strong></pre><h4>DELETE</h4><p>DELETE 호출은 GET 과 유사하며 delete() 함수를 통해 시작되고, delete() 함수 의 특성상 response는 Void.class 로 처리됩니다.</p><pre><strong>webClient.</strong>mutate<strong>()<br>         .</strong>baseUrl<strong>(&quot;https://some.com/api&quot;)<br>         .</strong>build<strong>()<br>         .delete()<br>         .</strong>uri<strong>(&quot;/resource/{ID}&quot;, id)<br>         .</strong>retrieve<strong>()<br>         .</strong>bodyToMono<strong>(Void.class);</strong></pre><h3>Synchronous Use</h3><p>WebClient 는 Reactive Stream 기반이므로 리턴값을 Mono 또는 Flux 로 전달받게 됩니다. Spring WebFlux를 이미 사용하고 있다면 문제가 없지만 Spring MVC를 사용하는 상황에서 WebClient 를 활용하고자 한다면 Mono 나 Flux 를 객체로 변환하거나 Java Stream 으로 변환해야 할 필요가 있습니다.</p><p>이럴 경우를 대비해서 Mono.block() 이나 Flux.blockFirst() 와 같은 blocking 함수가 존재하지만 block() 을 이용해서 객체로 변환하면 Reactive Pipeline 을 사용하는 장점이 없어지고 모든 호출이 main 쓰레드에서 호출되기 때문에 Spring 측에서는 block() 은 테스트 용도 외에는 가급적 사용하지 말라고 권고하고 있습니다.</p><p>대신 완벽한 Reactive 호출은 아니지만 Lazy Subscribe 를 통한 Stream 또는 Iterable 로 변환 시킬 수 있는 Flux.toStream() , Flux.toIterable() 함수를 제공하고 있습니다.</p><pre>List&lt;SomeData&gt; results =<br>    <strong>webClient.</strong>mutate<strong>()<br>             .</strong>baseUrl<strong>(&quot;https://some.com/api&quot;)<br>             .</strong>build<strong>()<br>             .get()<br>             .</strong>uri<strong>(&quot;/resource&quot;)<br>             .</strong>accept<strong>(MediaType.APPLICATION_JSON)<br>             .</strong>retrieve<strong>()<br>             .</strong>bodyToFlux<strong>(SomeData.class)<br>             .toStream()<br>             .collect(Collectors.toList());</strong></pre><p>Flux.toStream() 을 통해 데이터를 추가 처리하거나 List로 변환하여 사용할 수 있습니다.</p><p>Mono 에 대해서는</p><pre>SomeData data = <br>    <strong>webClient.</strong>mutate<strong>()<br>             .</strong>baseUrl<strong>(&quot;https://some.com/api&quot;)<br>             .</strong>build<strong>()<br>             .get()<br>             .</strong>uri<strong>(&quot;/resource/{ID}&quot;, id)<br>             .</strong>accept<strong>(MediaType.APPLICATION_JSON)<br>             .</strong>retrieve<strong>()<br>             .</strong>bodyToMono<strong>(SomeData.class)<br>             .flux()<br>             .toStream()<br>             .findFirst()<br>             .orElse(defaultValue);</strong></pre><p>Mono.flux() 를 통해 Flux 로 변환하고 findFirst() 를 통해 Optional 처리 하는것이 좋습니다. (이 때는 onError 처리가 필요합니다)</p><p>WebClient 는 RestTemplate 에 비해 사용성도 뛰어나고, 대규모 호출에 대해서도 자원 및 성능상 이점이 많아 WebClient 를 점진적으로 도입해 보실 것을 권해드립니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f92d295edc0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring WebFlux에서 Error 처리와 Retry 전략]]></title>
            <link>https://medium.com/@odysseymoon/spring-webflux%EC%97%90%EC%84%9C-error-%EC%B2%98%EB%A6%AC%EC%99%80-retry-%EC%A0%84%EB%9E%B5-a6bd2c024f6f?source=rss-2b38b424d093------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6bd2c024f6f</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[retrywhen]]></category>
            <dc:creator><![CDATA[달빛방랑]]></dc:creator>
            <pubDate>Thu, 07 May 2020 02:25:27 GMT</pubDate>
            <atom:updated>2020-05-07T02:25:27.821Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*iQIkpbG3dEvSI2iqE1vgPQ.png" /><figcaption><a href="https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html">https://projectreactor.io/docs/core/release/api/reactor/core/publisher/Flux.html</a></figcaption></figure><p>Spring WebFlux에서 Mono 또는 Flux를 처리하다 보면 Exception 등 Error가 발생하는 경우가 많습니다. 이 때 Exception을 throw하지 않고 Reactive Stream을 Graceful 하게 처리할 수 있는 다양한 방법과 Error 발생 시 취할 수 있는 Retry 전략에 대해 알아보도록 하겠습니다.</p><h3>Error Handling</h3><h4>1. onErrorReturn</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/411/1*AB5iFRjbKkBRfqlBQHX1Cw.png" /></figure><p>onErrorReturn은 Reactive Stream에서 Error가 발생했을 경우 정해진 Fallback value를 리턴해주는 방식입니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d421ff3d7627090e1a79a7cb48b9120/href">https://medium.com/media/5d421ff3d7627090e1a79a7cb48b9120/href</a></iframe><p>위와 같이 3가지 조건의 다른 parameter를 갖는 method가 정의되어 있습니다. 모든 Error에 대해 fallback value를 리턴하거나 / 특정 Error Type에 대해서만 처리하거나 / 특정 Predicate 에 부합될 경우에만 처리하는 등 각 상황에 맞게 전략적으로 사용할 수 있습니다.</p><p>예제 코드로 아래와 같이 확인해 보면</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2bd073f03df9f1d9d339c8ebec34e00d/href">https://medium.com/media/2bd073f03df9f1d9d339c8ebec34e00d/href</a></iframe><p>searchService.getPost(2) 를 호출 할 경우 RuntimeException 이 발생하고 정해진 Fallback value를 리턴하고 종료하는 것을 확인할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af0cab56a8fd3f4d37a344cff2d0cfd2/href">https://medium.com/media/af0cab56a8fd3f4d37a344cff2d0cfd2/href</a></iframe><p>onErrorReturn 은 Reactive Stream 처리 도중 Error가 발생할 경우 정해진 Fallback value를 리턴하고 나머지 element를 처리하지 않고 stream을 종료합니다.</p><h4>2. onErrorResume</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*SVOA9iiAZIlqFXWq7M-QSw.png" /></figure><p>onErrorResume은 Reactive Stream에서 Error가 발생했을 경우 Fallback publisher를 구독하도록 전환해주는 방식입니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a0cf81fcdfa7a743ae619842d03cfce/href">https://medium.com/media/6a0cf81fcdfa7a743ae619842d03cfce/href</a></iframe><p>onErrorResume 또한 3가지 조건의 parameter를 갖는 상황별 method가 정의되어 있습니다.</p><p>특정 Exception Type에 대한 처리 예제를 보면</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70481c6ce580527a842880303092aa5d/href">https://medium.com/media/70481c6ce580527a842880303092aa5d/href</a></iframe><p>searchService.getPost(2) 를 호출 할 경우 Exception 이 발생하고 Fallback Publisher를 subscribe하는 결과를 확인 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db2011403579b25ab4a7a224df4256c0/href">https://medium.com/media/db2011403579b25ab4a7a224df4256c0/href</a></iframe><p>onErrorResume 은 Reactive Stream 처리 도중 Error가 발생할 경우 정해진 Fallback Function 을 통해 새로운 Publisher로 대체하고 나머지 element는 처리하지 않고 stream을 종료합니다.</p><h4>3. onErrorContinue</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*gFq5fPYR1GriuzbP0B3yLg.png" /></figure><p>onErrorContinue는 Reactive Stream에서 Error가 발생했을 경우 Error를 처리해 주고 남은 Stream element들을 계속 처리해주는 방식입니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54677d306f514e53675ff30a70cd9c9b/href">https://medium.com/media/54677d306f514e53675ff30a70cd9c9b/href</a></iframe><p>onErrorContinue 또한 동일하게 3가지 조건의 parameter를 갖는 상황별 method가 정의되어 있으며, 이번에는 Predicate 에 대한 예제를 알아보겠습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e09099cd43d597fd7752bb02e9941c7/href">https://medium.com/media/3e09099cd43d597fd7752bb02e9941c7/href</a></iframe><p>searchService.getPost(2) 를 호출 했을 경우 RuntimeException 이 발생하고, onErrorContinue 의 Predicate 조건에 따라 “Mock”이라는 단어가 포함되어 있으므로 Error를 logging하고 다음 Stream element를 처리합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea55f6e6d614acdce697491d0e729125/href">https://medium.com/media/ea55f6e6d614acdce697491d0e729125/href</a></iframe><p>onErrorContinue 는 Reactive Stream 처리 도중 Error가 발생할 경우 Consumer 를 통해 Error를 처리하고 나머지 element를 계속 처리합니다.</p><h4>Retry Strategy</h4><h4>1. retry</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/814/1*5uCZWm49jajZ8VUXr9QKWQ.png" /></figure><p>retry 는 Error 발생 시 Reactive Stream을 처음 부터 다시 subscribe 합니다. 하지만 retry 를 아무 조건없이 사용하게 되면 무한정 retry를 시도하기 때문에 대상 stream에 과부하가 걸릴 수 있습니다.</p><p>이런 이유 때문에 기본 retry 를 이용하기 보다는 최대 재시도 횟수를 제한하는 파라미터가 추가된 method를 주로 사용합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*7-v8o7aS4n_qL0WwqAN6Gw.png" /></figure><p>retry(long numRetries) 를 이용하면 Reactive Stream에서 에러 발생 시 최대 numRetries만큼 재시도를 하고 그래도 에러가 발생하면 에러를 리턴하게 됩니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e303df4f6fe08cbee54fe023eb56727/href">https://medium.com/media/0e303df4f6fe08cbee54fe023eb56727/href</a></iframe><p>searchService.getPost(2) 호출 시 2번 에러가 나고 이후에 정상처리되게 설정하면 아래와 같이 두 번의 재시도 후 정상 처리되는 것을 확인 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de9dad760d33bee01f5e812d47a37ad7/href">https://medium.com/media/de9dad760d33bee01f5e812d47a37ad7/href</a></iframe><p>retry 를 이용하면 Reactive Stream에서 에러 발생 시 해당 Stream을 다시 Subscribe하여 재처리를 시도하며 최대 재시도 횟수를 설정 할 수 있습니다.</p><h4>2. retryWhen</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*gFeC_RjqEUikeS_N3SIUKg.png" /></figure><p>도식을 보면 복잡해 보이지만 retryWhen 은 retry 조건을 다양하게 주고 싶을 때 RetrySpec 을 통해 원하는 조건에 따른 재시도가 가능하게 해주는 방식입니다.</p><p>대표적으로 사용되는 3가지 RetrySpec에 대해 알아보겠습니다.</p><h4>- Retry.max</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*q531YXqruC8UUmqYPCwTeg.png" /></figure><p>Retry.max(long max)는 retry(long numReties) 와 같은 기능을 합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64dd7cb0ac07c75966f14a1d6113fca6/href">https://medium.com/media/64dd7cb0ac07c75966f14a1d6113fca6/href</a></iframe><p>처리 결과를 보면 아래와 같이 두 번의 재시도 후에 정상 처리됨을 확인 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b549b40213a7a606f9f5f5c155bc7c25/href">https://medium.com/media/b549b40213a7a606f9f5f5c155bc7c25/href</a></iframe><h4>- Retry.fixedDelay</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*ScfHdiyfy_OfdfOZuXTiiA.png" /></figure><p>Retry.fixedDelay(long maxAttemps, Duration fixedDelay) 는 정해진 Duration 동안 delay를 가진 후 maxAttempts 만큼 Retry 를 시도합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5840faf48147b84fc4ed666a03d86a01/href">https://medium.com/media/5840faf48147b84fc4ed666a03d86a01/href</a></iframe><p>위와 같이 2초의 delay와 최대 2회 재시도를 설정 했을 경우, 약 2초 간격으로 새로운 Scheduler에서 재시도를 처리한 것을 확인 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bce57d9ae5909b3d0ab13b48e24930fb/href">https://medium.com/media/bce57d9ae5909b3d0ab13b48e24930fb/href</a></iframe><h4>- Retry.backoff</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*HB8upTYeNxsPK9uqeSWWOQ.png" /></figure><p>Retry.backoff(long maxAttempts, Duration minBackoff) 는 Reactive Stream에서 에러가 발생 할 경우 최소 minBackoff 만큼 delay 후 maxAttemps 만큼 Retry 를 시도합니다. Retry.fixedDelay 와의 차이점은 에러가 계속 발생 할 경우 Delay 시간이 지수 형태로 점점 늘어난다는 점입니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db88a8b7cc00493bf25dd8e9bbc4112a/href">https://medium.com/media/db88a8b7cc00493bf25dd8e9bbc4112a/href</a></iframe><p>실행 결과를 보면 delay 시간이 최소 2초에서 점점 늘어나는 것을 볼 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9584984a19dfa7c32da80098e6c99752/href">https://medium.com/media/9584984a19dfa7c32da80098e6c99752/href</a></iframe><p>견고한 어플리케이션 개발에서 중요한 것 하나가 Error 처리입니다. Reactive Stream에서 제공하는 onError 관련 메소드와 Retry 를 잘 조합하면 예상치 못한 에러 상황에서도 안정적으로 서비스를 제공 할 수 있습니다.</p><p>관련 소스는 아래 GitHub에서 확인 할 수 있습니다.</p><p><a href="https://github.com/Odysseymoon/spring-webflux-retry">Odysseymoon/spring-webflux-retry</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6bd2c024f6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Data JPA에서 GroupBy 처리하기]]></title>
            <link>https://medium.com/@odysseymoon/spring-data-jpa%EC%97%90%EC%84%9C-groupby-%EC%B2%98%EB%A6%AC%ED%95%98%EA%B8%B0-82cddc6e5d4a?source=rss-2b38b424d093------2</link>
            <guid isPermaLink="false">https://medium.com/p/82cddc6e5d4a</guid>
            <category><![CDATA[spring-data-jpa]]></category>
            <category><![CDATA[querydsl]]></category>
            <category><![CDATA[group-by]]></category>
            <dc:creator><![CDATA[달빛방랑]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 04:30:49 GMT</pubDate>
            <atom:updated>2020-04-27T04:30:49.158Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xGyw3shWVhJGCQP-5opU5g.png" /></figure><p>Spring Data JPA에서는 GroupBy 를 사용하려면 어떻게 해야 할까요? <a href="https://docs.spring.io/spring-data/jpa/docs/2.2.6.RELEASE/reference/html/#repository-query-keywords">Reference Doc</a> 에서도 Group By 관련 키워드는 찾아보기 힘듭니다. Group By를 이용하려면 다른 방식을 적용해야 하는데요, Spring Data JPA에서 Group By를 사용하기 위한 4가지 방식에 대해 알아보겠습니다.</p><h3>Conditions</h3><p>일단 Database Table이 다음과 같이 정의 되어 있다고 가정할 때</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca8fafbef9b31f228c0bdc819872658d/href">https://medium.com/media/ca8fafbef9b31f228c0bdc819872658d/href</a></iframe><p>Entity 를 다음과 같이 생성합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d4eb18c50fc7f87c15d06c7a96b1eb3/href">https://medium.com/media/1d4eb18c50fc7f87c15d06c7a96b1eb3/href</a></iframe><p>report 테이블에서 year 별로 Report 엔티티의 각 합산값을 구해보겠습니다.</p><h3>사용법</h3><h4>Java8 Stream 활용</h4><p>순수 Application 단에서 Java 8의 Stream을 이용해 Entity 를 Group By 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/01fcadc097385af0a272c40318680ff8/href">https://medium.com/media/01fcadc097385af0a272c40318680ff8/href</a></iframe><p>Java8에 collect 를 이용하면 다양한 groupBy를 사용할 수 있습니다.<br>위 예제에서는 sum 값을 구하는 필드가 한 개 이상이기 때문에 Collectors.toMap 을 이용하여 Report.getYear() 를 기준으로 YearReportSum 을 생성하는 방식으로 사용하였습니다.</p><p>Java8 Stream을 사용하게 되면 어플리케이션 단에서 구현된 내용을 쉽게 수정하거나 파악할 수 있는 장점이 있지만 전체 Data를 어플리케이션에서 group by 를 하기 때문에 데이터가 많아지면 많아질 수 록 속도가 느려지고 메모리를 많이 사용하게 됩니다. 적은 데이터에 대해 빠른 구현으로는 적합하지만 많은 데이터에 대해서는 적절한 방식은 아닙니다.</p><h4>JPQL 활용</h4><p>JPA에 JPQL 과 <a href="https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections">Projection</a> 을 이용해서 Entity가 아닌 DTO에 Query 결과값을 담을 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af45e7dd04bf232a3af0c458f0e5af0a/href">https://medium.com/media/af45e7dd04bf232a3af0c458f0e5af0a/href</a></iframe><p>JPQL 을 이용하면 Query에 대한 타입 안정성과 Query 안정성을 바로 확인 할 수 있지만 Projection 을 사용할 때 new 를 통해 생성자를 쿼리 내에서 호출해줘야 해서 Query가 장황해지는 단점이 있습니다.</p><h4>Native Query 활용</h4><p>Native Query에 대해 Entity 가 아닌 Return값을 반환받기 위해서는 Interface based Projection 을 활용해야 합니다.</p><p>Interface 를 다음과 같이 선언합니다.</p><pre>public interface YearReportSumInterface {<br><br>    Integer getYear();<br>    BigDecimal getSmallSum();<br>    BigDecimal getMajorSum();<br>    BigDecimal getTotalSum();<br><br>}</pre><p>선언된 Interface 에 맞게 Native Query를 작성합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07b065b71b2c38e3fb06c031bb5b43a1/href">https://medium.com/media/07b065b71b2c38e3fb06c031bb5b43a1/href</a></iframe><p>JPQL 과 유사하지만 nativeQuery=true 를 통해 순수 Query로 작성되어 있으며, Select된 각 컬럼을 Interface 명에 맞춰 Alias를 설정해 줘야 합니다.</p><p>Native Query 를 활용하게 되면 쿼리 자체를 Database에서 빠르게 검증 가능하지만, 반환된 Interface 를 별도의 DTO로 변환해야 할 필요성이 생깁니다.</p><h4>QueryDSL 활용</h4><p>QueryDSL 을 활용한 Group By 쿼리는 JPAQuery 를 직접 활용해야 합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/480c6662f20d0b913ea567e1a68be33c/href">https://medium.com/media/480c6662f20d0b913ea567e1a68be33c/href</a></iframe><p>QueryDSL 에서 Group By 를 사용하기 위해서는 EntityManager 를 통해 JPAQuery 를 직접 생성해서 사용해야 하는 단점이 있지만, QueryDSL 의 장점인 다양한 조건의 쿼리를 생성할 수 있다는 장점이 있습니다. ( Optional 한 쿼리 조건을 각각 적용 가능)</p><h3>성능</h3><p>간단하게 local에서 약 230건의 데이터에 대해 각각 100회씩 호출 하였을 경우 API 응답 시간 성능 측정 결과는 아래와 같았습니다.<br>(개별 환경에 따라 다를 수 있습니다)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GC_gTpi-kkQQhkDIRuxoCQ.png" /></figure><p>결과에서 보는 것과 같이 Java8 Stream이 가장 속도가 느리며 나머지는 실제 쿼리가 비슷하기 때문에 평균 응답시간도 같게 나왔습니다.</p><p>다만 JPQL과 QueryDSL은 초기 쿼리 파싱 때문에 Max 속도가 다른것을 볼 수 있습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82cddc6e5d4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JPA Entity에 Enum 타입 적용하기]]></title>
            <link>https://medium.com/@odysseymoon/jpa-entity%EC%97%90-enum-%ED%83%80%EC%9E%85-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0-9ce2f6ee3148?source=rss-2b38b424d093------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ce2f6ee3148</guid>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[entity]]></category>
            <category><![CDATA[jpa]]></category>
            <dc:creator><![CDATA[달빛방랑]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 02:16:37 GMT</pubDate>
            <atom:updated>2020-04-23T02:16:37.676Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hexxgt494hqpjWZVMwpwaQ.png" /></figure><h3>When</h3><p>JPA 사용 시 True/False 데이터나 Y/N 형태의 코드로 저장하는 컬럼들을 자주 사용하게 됩니다. 이 때 DB 컬럼을 char(1) 또는 tinyint(1) 아니면 boolean 형태로 정의하고 데이터를 저장하게 되는데, 해당 컬럼에 맞춰 데이터 타입을 String이나 Integer 로 설정하게 되면 어플리케이션 내부에서 정합성을 체크하기가 힘듭니다.</p><p>이런 경우 Java Enum 을 활용하여 REST API 파라미터 부터 JPA Entity까지 데이터 타입을 보호하는 방법을 알아보겠습니다.</p><h3>Given</h3><p>MySQL 을 이용한 User 테이블이 다음과 같이 정의 되었을 경우 is_verified 컬럼을 JPA 에서 Enum 타입으로 맵핑해 보도록 하겠습니다.</p><pre><strong>CREATE TABLE IF NOT EXISTS `user` (<br>    `user_id`         varchar(30)  NOT NULL COMMENT &#39;사용자아이디&#39;,<br>    `password`        varchar(255) NOT NULL COMMENT &#39;비밀번호&#39;,<br>    `is_verified`     char(1)      NOT NULL COMMENT &#39;T or F&#39;,<br>    `update_date`     timestamp    NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,<br>    PRIMARY KEY (`user_id`)<br>) ENGINE</strong>=InnoDB <strong>DEFAULT CHARSET</strong>=utf8mb4 <strong>COLLATE</strong>=utf8mb4_unicode_ci <strong>COMMENT</strong>=<strong>&#39;사용자정보&#39;;</strong></pre><h3>Then</h3><h4>JPA Entity 맵핑</h4><p>Enum 타입을 이용한 코드 클래스를 정의하기 위해 기본 인터페이스를 하나 생성합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fc88b646d7f5992a47d2b8b4dbf29e4/href">https://medium.com/media/9fc88b646d7f5992a47d2b8b4dbf29e4/href</a></iframe><p>Entity에서 사용할 코드 클래스를 정의합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99682a4158a0ff8164643fa6a4c31daa/href">https://medium.com/media/99682a4158a0ff8164643fa6a4c31daa/href</a></iframe><ul><li>DB 컬럼에 NOT NULL 을 적용해 놓았기 때문에 NULL 코드는 삭제 가능합니다. 다만 Spring MVC나 Spring WebFlux에서 @RequestBody 파라미터로 같이 사용할 경우 NULL 코드를 활용 할 수 있습니다.</li></ul><p>JPA Entity Column Convert를 위해 BaseEnumCode&lt;T&gt; 에 대한 AttributeConverter 를 정의합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/be94f22c7f5520081471c6b0079850e8/href">https://medium.com/media/be94f22c7f5520081471c6b0079850e8/href</a></iframe><ul><li>BaseEnumCode&lt;T&gt; 를 상속받는 Enum 에 대한 Converter이기 때문에 &lt;T&gt; 타입에 대한 values를 알 수 없어서 abstract 클래스로 정의합니다.</li></ul><p>이제 위에서 정의한 TFCode&lt;String&gt; enum에 대한 Converter를 다음과 같이 구현합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd29d61112bb1ed9433aeea6fefcd749/href">https://medium.com/media/fd29d61112bb1ed9433aeea6fefcd749/href</a></iframe><p>이제 위에서 선언한 Enum 과 Converter 를 활용해 User Entity를 다음과 같이 정의 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b777baae71f634ad2cdc125708c4e0/href">https://medium.com/media/61b777baae71f634ad2cdc125708c4e0/href</a></iframe><p>이렇게 정의한 User Entity에 isVerified 는 Enum 타입을 활용해 어플리케이션 내부에서 타입 안정성을 확보 할 수 있습니다.</p><h4>WebFlux Validation에서 활용</h4><p>마찮가지로 TFCode 를 Spring WebFlux API 호출 시 타입 안정성 및 @Valid 를 통한 파라미터 Validation에서 활용하는 방법을 알아보겠습니다.</p><p>기본적으로 WebMVC / WebFlux에 Request Parameter에 Enum타입을 사용하는 것 만으로도 Type Casting 에러를 통해 안정성을 확보 할 수 있습니다.<br>여기에서 한 걸음 더 나아가 Custom ConstraintValidator를 이용해서 Enum 클래스에 대한 더 세세한 컨트롤을 해보겠습니다.</p><p>먼저 Constraint 를 위한 Annotation 을 하나 선언합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cb22647560dafe8a33a64243ca63607/href">https://medium.com/media/5cb22647560dafe8a33a64243ca63607/href</a></iframe><p>@Constraint 에 적용할 Validator를 정의합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1de311f9f6a8f9d55312fa66934bd00/href">https://medium.com/media/e1de311f9f6a8f9d55312fa66934bd00/href</a></iframe><p>위에서 정의한 Annotation 을 적용한 Request Parameter 클래스를 다음과 같이 정의 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/999ed33f0a139bbffa1d5c5fcb69c636/href">https://medium.com/media/999ed33f0a139bbffa1d5c5fcb69c636/href</a></iframe><ul><li>Parameter로 받은 TFCode 중에서 TFCode.TRUE 와 TFCode.FALSE 만 사용가능 하도록 Validation을 적용한 예제입니다.</li></ul><p>Spring WebFlux REST API 호출에서는 다음과 같이 @Valid를 통해 ConstraintValidator 를 적용 가능합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd0ca3da0e13891c03584b0ad5498711/href">https://medium.com/media/fd0ca3da0e13891c03584b0ad5498711/href</a></iframe><h3>결론</h3><p>여러 어플리케이션이 같은 DB 컬럼을 사용하며 업데이트 될 때 예기치 않게 데이터 정합성이 깨지는 경우나, 의도치 않은 데이터 타입이 들어오면서 에러가 나는 경우가 많습니다. 이럴 때 Enum 과 같은 타입을 이용하면 최소한의 데이터 정합성을 쉽게 확보할 수 있습니다.</p><ul><li>관련 Source 는 아래 GitHub에서 확인할 수 있습니다.</li></ul><p><a href="https://github.com/Odysseymoon/spring-jpa-enum-converter">Odysseymoon/spring-jpa-enum-converter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ce2f6ee3148" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring WebFlux Session with Redis]]></title>
            <link>https://medium.com/@odysseymoon/spring-webflux-session-with-redis-3c1f82de81?source=rss-2b38b424d093------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c1f82de81</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[spring-session]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[달빛방랑]]></dc:creator>
            <pubDate>Tue, 21 Apr 2020 09:04:42 GMT</pubDate>
            <atom:updated>2020-04-21T09:05:52.977Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eDtNVTXJ_9ONaDhf.png" /></figure><h3>Spring Session</h3><p>유저의 로그인이 필요한 관리자 어플 같은 경우에는 단기적인 보안만 필요하기 때문에 간단하게 Session을 많이 이용합니다. Spring 진영에서도 Spring Session 프로젝트를 통해서 이를 지원하고 있습니다.</p><p><a href="https://spring.io/projects/spring-session">Spring Session</a></p><p>WAS(Web Application Server)에서 Session은 기본적으로 서버 단위에 저장되기 때문에 Application이 여러 서버에 분산되어 있는 경우에는 Redis와 같은 별도 Storage에 Session을 저장하는 방식으로 분산환경을 구성합니다.</p><p>이번 샘플에서는 Spring Redis Session을 통해 Spring WebFlux REST API 서비스에 Session을 사용하는 방법에 대해 알아보겠습니다.</p><h3>Maven 구성</h3><p>우선 기본적인 라이브러리를 다음과 같이 pom.xml 파일에 추가해 줍니다.</p><pre><em>&lt;!-- Spring --&gt;<br></em><strong>&lt;</strong><em>dependency</em><strong>&gt;<br>    &lt;</strong><em>groupId</em><strong>&gt;</strong><em>org.springframework.boot</em><strong>&lt;/</strong><em>groupId</em><strong>&gt;<br>    &lt;</strong><em>artifactId</em><strong>&gt;</strong><em>spring-boot-starter</em><strong>&lt;/</strong><em>artifactId</em><strong>&gt;<br>&lt;/</strong><em>dependency</em><strong>&gt;<br><br>&lt;</strong><em>dependency</em><strong>&gt;<br>    &lt;</strong><em>groupId</em><strong>&gt;</strong><em>org.springframework.boot</em><strong>&lt;/</strong><em>groupId</em><strong>&gt;<br>    &lt;</strong><em>artifactId</em><strong>&gt;</strong><em>spring-boot-starter-data-jpa</em><strong>&lt;/</strong><em>artifactId</em><strong>&gt;<br>&lt;/</strong><em>dependency</em><strong>&gt;<br><br>&lt;</strong><em>dependency</em><strong>&gt;<br>    &lt;</strong><em>groupId</em><strong>&gt;</strong><em>org.springframework.boot</em><strong>&lt;/</strong><em>groupId</em><strong>&gt;<br>    &lt;</strong><em>artifactId</em><strong>&gt;</strong><em>spring-boot-starter-webflux</em><strong>&lt;/</strong><em>artifactId</em><strong>&gt;<br>&lt;/</strong><em>dependency</em><strong>&gt;<br><br>&lt;</strong><em>dependency</em><strong>&gt;<br>    &lt;</strong><em>groupId</em><strong>&gt;</strong><em>org.springframework.session</em><strong>&lt;/</strong><em>groupId</em><strong>&gt;<br>    &lt;</strong><em>artifactId</em><strong>&gt;</strong><em>spring-session-data-redis</em><strong>&lt;/</strong><em>artifactId</em><strong>&gt;<br>&lt;/</strong><em>dependency</em><strong>&gt;<br><br>&lt;</strong><em>dependency</em><strong>&gt;<br>    &lt;</strong><em>groupId</em><strong>&gt;</strong><em>org.springframework.boot</em><strong>&lt;/</strong><em>groupId</em><strong>&gt;<br>    &lt;</strong><em>artifactId</em><strong>&gt;</strong><em>spring-boot-starter-data-redis-reactive</em><strong>&lt;/</strong><em>artifactId</em><strong>&gt;<br>&lt;/</strong><em>dependency</em><strong>&gt;<br><br></strong><em>&lt;!--Common Pool --&gt;<br></em><strong>&lt;</strong><em>dependency</em><strong>&gt;<br>    &lt;</strong><em>groupId</em><strong>&gt;</strong><em>org.apache.commons</em><strong>&lt;/</strong><em>groupId</em><strong>&gt;<br>    &lt;</strong><em>artifactId</em><strong>&gt;</strong><em>commons-pool2</em><strong>&lt;/</strong><em>artifactId</em><strong>&gt;<br>    &lt;</strong><em>version</em><strong>&gt;</strong><em>2.8.0</em><strong>&lt;/</strong><em>version</em><strong>&gt;<br>&lt;/</strong><em>dependency</em><strong>&gt;</strong></pre><ul><li>Spring Boot 설정을 통해 Connection Pool을 자동구성 하려면 Apache common-pool2 라이브러리가 꼭 추가 되어야 합니다.</li></ul><h3>Property 파일 구성</h3><p>application.yaml 을 통해 Redis Connection 정보와 Spring Session 타입을 지정해 줍니다.</p><pre><em>spring:<br>  redis:<br>    host: localhost<br>    port: 16379<br>    password: {REDIS_PASSWORD}<br>    lettuce:<br>      pool:<br>        min-idle: 2<br>        max-idle: 5<br>        max-active: 10<br>  session:<br>    store-type: redis<br>    </em>redis:<br>        flush-mode: immediate</pre><ul><li>lettuce를 통한 Connection Pool을 구성하고 Session Storage를 Redis로 지정하여 Redis Session을 사용하도록 설정합니다.</li><li>Session 관련 나머지 설정은 기본값으로 두어도 상관없지만 spring.session.redis.flush-mode 값을 immediate 로 설정하면 가능한 빨리 Session을 Redis Storage에 저장하게 됩니다.</li></ul><h3>Application 설정</h3><p>Annotation 을 통하여 Session과 Redis를 활성화 시키고 Session Object를 저장하기 위해 RedisTemplate을 재정의 합니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39102a8fb9cb331fe40a6473e9e63295/href">https://medium.com/media/39102a8fb9cb331fe40a6473e9e63295/href</a></iframe><ul><li>@EnableRedisWebSession 을 통해 Redis Session을 설정하고 maxInactiveIntervalInSeconds 에 Session Timeout 값(초)를 지정합니다.</li><li>@EnableRedisRepositories 를 통해 Redis Repository를 활성화 하고 RedisTemplate을 정의합니다.</li><li>REST API 서비스 같은 경우에는 UI가 없기 때문에 Session 정보를 Header에 담아 전달하는 방식을 선호하게 됩니다. WebSessionIdResolver 를 재정의해서 “X-AUTH-HEADER” 해더를 Session ID로 인식하게 합니다.</li></ul><h3>Session Filter 설정</h3><p>Session 체크를 위해 Spring WebFlux 에 WebFilter 를 통해 SessionFilter를 정의해 줍니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10e1d1a6a3fbb8696a6c21298a5b15f8/href">https://medium.com/media/10e1d1a6a3fbb8696a6c21298a5b15f8/href</a></iframe><h3>REST 사용법</h3><h4>SignIn 후 SessionID 전달</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5abcdb4cc2b7defabb5b3ab285ab1298/href">https://medium.com/media/5abcdb4cc2b7defabb5b3ab285ab1298/href</a></iframe><ul><li>정상적으로 로그인이 되었을 경우 ResponseEntity 객체를 통해 SessionID를 Header로 전달해 줍니다.</li></ul><h4>@RestController 에서 Session 객체 사용</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaa6d42efe394fa21c0bd0431e2fbe85/href">https://medium.com/media/aaa6d42efe394fa21c0bd0431e2fbe85/href</a></iframe><ul><li>@RestController 에서는 WebSession 파라미터를 통해 Session 객체에 바로 접근할 수도 있으며</li><li>@SessionAttribute 를 통해 Session에 저장된 객체를 바로 파라미터로 받아 사용할 수 도 있습니다.</li></ul><h4>Redis Session 확인</h4><p>Redis CLI를 통해 Redis에 접속해 보면 다음과 같이 Redis Session이 저장되어 있는것을 확인 할 수 있습니다.</p><pre>127.0.0.1:6379&gt; keys *<br>1) &quot;spring:session:sessions:cc81b08c-a134-4899-8bb9-ba2545af9653&quot;<br>2) &quot;spring:session:sessions:65c1e7c9-d070-40b5-a00a-46d6a60e72bb&quot;<br>3) &quot;spring:session:sessions:9bce9dd1-ae39-42ed-8600-6b6c984c9817&quot;<br>127.0.0.1:6379&gt; hkeys spring:session:sessions:9bce9dd1-ae39-42ed-8600-6b6c984c9817<br>1) &quot;maxInactiveInterval&quot;<br>2) &quot;creationTime&quot;<br>3) &quot;lastAccessedTime&quot;<br>4) &quot;sessionAttr:user&quot;<br>127.0.0.1:6379&gt; hget spring:session:sessions:9bce9dd1-ae39-42ed-8600-6b6c984c9817 sessionAttr:user<br>&quot;\xac\xed\x00\x05sr\x00\x1bmoon.odyssey.model.UserInfo}\x8ea*\x9f\xc0`\xcb\x02\x00\x01L\x00\x06userIdt\x00\x12Ljava/lang/String;xpt\x00\btestUser&quot;</pre><h3>결론</h3><p>Spring Session 을 통하면 쉽고 빠르게 Session 관리를 구축할 수 있으며 다양한 Storage를 지원하기 때문에 프로젝트 환경에 맞는 분산 세션 환경을 구성할 수 있습니다.</p><ul><li>관련 Source 는 아래 GitHub에서 확인할 수 있습니다.</li></ul><p><a href="https://github.com/Odysseymoon/spring-webflux-redis-session">Odysseymoon/spring-webflux-redis-session</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c1f82de81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Property Encryption]]></title>
            <link>https://medium.com/@odysseymoon/spring-property-encryption-bad69ce708c2?source=rss-2b38b424d093------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad69ce708c2</guid>
            <category><![CDATA[jasypt]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[encryption]]></category>
            <dc:creator><![CDATA[달빛방랑]]></dc:creator>
            <pubDate>Mon, 20 Apr 2020 05:43:56 GMT</pubDate>
            <atom:updated>2020-04-20T09:04:45.337Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hp-ZGmy-ET-NE9Ra-vs-bg.png" /></figure><p>Spring Framework 또는 Spring Boot 기반 프로젝트에서는 application.properties 또는 application.yaml에 다양한 정보를 저장하게 됩니다. 이 때 데이터베이스 로그인 정보나 Secret key와 같은 민감한 정보도 함께 노출될 가능성이 있다는 문제가 있습니다.</p><p>GitHub 등과 같은 저장소에서도 프로젝트를 실수로 public으로 전환하면서 이런 민감한 정보들이 노출되는 경우가 많습니다. <br>위와 같은 유출 사고에 대비해서 최소한의 암호화를 통한 property 정보를 숨기는 방법에 대해 알아보겠습니다.</p><h3><strong>jasypt-spring-boot-starter</strong></h3><p>Java 진영에서 많이 쓰이는 Encryption 라이브러리 중 하나가 Jasypt 입니다.</p><p><a href="http://www.jasypt.org/">Jasypt: Java simplified encryption - Jasypt: Java simplified encryption - Main</a></p><p>Jasypt 만으로도 충분히 사용 가능하기는 하지만 Property들에 대한 Get/Set을 별도로 작업해 줘야 하기때문에 번거로울 수 밖에 없습니다.</p><p>이러한 번거로움을 덜어주고 Spring Boot에서도 바로 쓸 수 있도록 만든<br>jasypt-spring-boot-starter 라는 개인 프로젝트가 존재합니다. (아직 Spring 진영에서 공식으로 지원하는 라이브러리는 없습니다)</p><p><a href="https://github.com/ulisesbocchio/jasypt-spring-boot">GitHub - ulisesbocchio/jasypt-spring-boot: Jasypt integration for Spring boot</a></p><h3>어떻게 사용하나요?</h3><p>먼저 라이브러리를 사용하기 위해 Maven 모듈을 추가해 줍니다.<br>그리고 암호화 라이브러리로 Bouncy Castle을 사용하기로 합니다.<br>기존 Oracle JDK 같은 경우 강화된 암호화 알고리즘을 사용하기 위해서는 <a href="https://www.oracle.com/java/technologies/javase-jce8-downloads.html">Java Cryptography Extension</a> 을 JDK 자체에 추가로 설치해 줘야 하기 때문에 어플리케이션의 독립성과 암호화 알고리즘 확장을 위해 Bouncy Castle 라이브러리를 별도로 사용하도록 합니다.</p><p><a href="https://bouncycastle.org/documentation.html">bouncycastle.org</a></p><ul><li>pom.xml</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d61485834f1d433430a4bb0179d32fd/href">https://medium.com/media/0d61485834f1d433430a4bb0179d32fd/href</a></iframe><p>암복화화가 가능하고 Bouncy Castle 라이브러리를 사용하도록 Encyptor Bean을 재정의 해줍니다.</p><ul><li>StringEncryptor.java</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/890bdcd37283b150e58fa0d33d062a01/href">https://medium.com/media/890bdcd37283b150e58fa0d33d062a01/href</a></iframe><p>Bean 내부에 패스워드가 저장 되길 원하지 않는다면 System property 를 이용해 패스워드를 설정 할 수 있습니다.<br>jar 또는 tomcat 구동 시 -Djasypt.encryptor.password=MyPassword 를 적용하여 소스 코드 상에서 패스워드가 유출되는것을 막을 수 있습니다.<br>(이 경우에는 application.yaml이나 Database에 암호화된 정보들이 해당 패스워드에 의한 암호화된 값과 매칭되도록 미리 수정되어야 합니다)</p><p>작성한 Bean 이 정상 작동 하는 지 다음과 같은 Test 클래스를 통해 확인하거나 암호화된 값을 확인 할 수 있습니다.</p><ul><li>Test Case</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c7170a9ee1e056895fce5de825818a7/href">https://medium.com/media/4c7170a9ee1e056895fce5de825818a7/href</a></iframe><p>테스트를 통해 나온 값을 application.yaml 에 ENC()를 통해 적용하면 Spring Boot이 실행되면서 암호화된 property를 자동으로 복호화해서 적용해 줍니다.</p><ul><li>application.yaml</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e829c0b17aa31576e5b74f917fda1db7/href">https://medium.com/media/e829c0b17aa31576e5b74f917fda1db7/href</a></iframe><h3>DB에 암복호화 설정</h3><p>JPA를 통해 Entity를 저장할 때 민감한 정보들에 대해서는 DB 유출 사고에도 대비해야 합니다. 앞서 만든 Encryptor를 JPA의 Converter를 통해 Entity에 자동 적용할 수 있습니다.</p><p>String 컬럼에 대해 아래와 같이 Convert를 정의합니다.</p><ul><li>StringEncryptConverter</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22cbe73201580ae2d6ad0f3e6ec14056/href">https://medium.com/media/22cbe73201580ae2d6ad0f3e6ec14056/href</a></iframe><p>Entity에 Converter를 적용하면 DB에 암호화된 상태로 값을 저장하고<br>읽어 들일 때 자동으로 복호화 합니다.</p><ul><li>Entity</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1fa3d382d38c5189070a70592cc96b0/href">https://medium.com/media/a1fa3d382d38c5189070a70592cc96b0/href</a></iframe><h3>결론</h3><p>많은 사람들이 쉽게 간과하는게 보안에 관련된 사항들입니다. 때론 번거롭기도 하지만 그러한 점 때문에 자주 보안사고가 발생하기도 합니다.<br>조금만 작업하면 가장 기본적인 항목들에 대한 암복호화가 가능하니 최소한의 안전장치라 생각하고 이 부분만은 꼭 프로젝트에 적용했으면 좋겠습니다.</p><ul><li>* 관련 Source 는 아래 GitHub에서 확인할 수 있습니다.</li></ul><p><a href="https://github.com/Odysseymoon/spring-property-encryption">Odysseymoon/spring-property-encryption</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad69ce708c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>