<?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 Renan Barbioni on Medium]]></title>
        <description><![CDATA[Stories by Renan Barbioni on Medium]]></description>
        <link>https://medium.com/@rbarbioni?source=rss-33bd97ada739------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*-gANZv_yHcKQn-FwCyQuZQ.jpeg</url>
            <title>Stories by Renan Barbioni on Medium</title>
            <link>https://medium.com/@rbarbioni?source=rss-33bd97ada739------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 03:27:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rbarbioni/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[Criando Microservices com Programação Funcional Reativa em Java]]></title>
            <link>https://medium.com/@rbarbioni/criando-microservices-com-programa%C3%A7%C3%A3o-funcional-reativa-em-java-96069ca1b652?source=rss-33bd97ada739------2</link>
            <guid isPermaLink="false">https://medium.com/p/96069ca1b652</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[brazil]]></category>
            <dc:creator><![CDATA[Renan Barbioni]]></dc:creator>
            <pubDate>Fri, 26 May 2017 13:25:37 GMT</pubDate>
            <atom:updated>2017-05-26T13:46:09.620Z</atom:updated>
            <content:encoded><![CDATA[<p>Aprenda a criar API Reativa, Non-Blocking e funcional com Spring 5.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Gon8Y2H9c2Qc0UEiwC9nMA.jpeg" /></figure><p>Neste artigo, vou abordar um tema que ainda não está sendo utilizado pela maioria dos desenvolvedores da plataforma Java. Desde que o Java 8 foi lançado em Março de 2014, dentre as inúmeras melhorias da plataforma, Heap, PermGen, GC e etc… O que teve maior destaque foram as Expressões Lambda e Collection Streams.<br>Para não fugir muito do objetivo do artigo, não foi aprofundar muito em Lambdas e Collections Streams, porém caso não saiba do que estou falando abaixo os links para dar uma lida.</p><p><a href="http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html">Whats News Java 8</a><br><a href="https://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html">Lambda Expressions</a><br><a href="https://docs.oracle.com/javase/tutorial/collections/streams/">Collections Streams</a></p><h3>Spring-Boot 2.0</h3><p>Para este exemplo, foi utilizado Spring para a implementação da parte reativa, o Spring Foundation está preparando (Ainda em SNAPSHOT) uma série de recursos para tirarmos proveito do Java-8 e as novas implementações do Servlet 3.1 integralmente.<br>Para saber todas as novidades do Spring-Boot 2.0 abaixo o link:</p><p><a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M1-Release-Notes">Spring-Boot 2.0 Release Notes</a></p><h3>Spring Framework 5.0</h3><p>Junto com Spring-Boot 2.0 vem o Spring 5 que é a base das implementações, nesta versão estão sendo adicionados recursos bastante pertinentes para trabalharmos com Java 8 de forma “Mais Funcional”.<br>Para atender as definições de programação funcional na criação de API REST, o Spring adicionou o suporte ao <a href="http://projectreactor.io/">Projetc Reactor</a> que contém as implementações base para criarmos APIs de forma reativa.</p><p><a href="https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-the-Spring-Framework">Spring Framework 5.0 Whats News</a></p><p>Então agora o Java é um linguagem Funcional?<br>Não! A linguagem Java está “Aos Poucos” dando suporte maior a programação funcional, porém não é um linguagem puramente funcional assim como Haskel por exemplo.</p><h3>Programação Reativa</h3><p>Na nova versão do Spring foi adicionado o Spring-WebFlux que é uma alternativa para se trabalhar com MVC de forma Reativa, Assíncrona e não bloqueante. A fundação adicionou o Project Reactor e Netty-Server que contém implementações para funcionar com Servlet 3.1 com servidor embedded no start do Spring-Boot Application.<br>Para saber as motivações e detalhes sobre Reactive Spring, abaixo o link</p><p><a href="https://spring.io/blog/2016/02/09/reactive-spring">Reactive Spring</a></p><h3>Show-Me-Code</h3><p>O exemplo completo está no repositório <a href="https://github.com/rbarbioni/reactive-mongo-api">Github</a>. <br>Foi utilizado Gradle como build e dependency-management, Java-8, Spring-Boot 2.0, Spring-5, Netty-Server e MongoDB que está rodando na porta default 27017. Necessário criar um database chamado “test”.</p><p>Primeiro vamos a setup do projeto, build.gradle</p><pre>buildscript {<br>    ext {<br>        springBootVersion = &#39;2.0.0.BUILD-SNAPSHOT&#39;<br>    }<br>    repositories {<br>        mavenCentral()<br>        maven { url &#39;https://repo.spring.io/libs-snapshot&#39; }<br>    }<br>    dependencies {<br>        classpath &quot;org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}&quot;<br>    }<br>}</pre><pre>apply plugin: &#39;java&#39;<br>apply plugin: &#39;org.springframework.boot&#39;<br>apply plugin: &#39;io.spring.dependency-management&#39;</pre><pre>repositories {<br>    mavenLocal()<br>    mavenCentral()<br>    jcenter()<br>    maven { url &quot;http://repo.spring.io/release&quot; }<br>    maven { url &quot;http://repo.spring.io/milestone&quot; }<br>    maven { url &quot;http://repo.spring.io/snapshot&quot; }<br>}</pre><pre>dependencies {<br>    runtime(&quot;org.springframework.boot:spring-boot-devtools&quot;)<br>    compile(&quot;org.springframework.boot:spring-boot-starter-webflux&quot;)<br>    compile(&quot;org.springframework.boot:spring-boot-starter-data-mongodb-reactive&quot;)<br>    compile group: &#39;io.projectreactor.ipc&#39;, name: &#39;reactor-netty&#39;, version: &#39;0.6.3.RELEASE&#39;<br>}</pre><pre>task wrapper(type: Wrapper) {<br>    gradleVersion = &#39;3.4&#39;<br>}</pre><p>Repare que estou utilizando versão 2.0.0.SNAPSHOT</p><p>Netty-Server Configuration</p><pre>@Configuration<br>@EnableAutoConfiguration<br>@EnableReactiveMongoRepositories(basePackages = &quot;br.com.rbarbioni.netty&quot;)<br>public class HttpServerConfig {</pre><pre>    @Autowired<br>    private Environment environment;</pre><pre>    @Bean<br>    public HttpServer httpServer(RouterFunction&lt;?&gt; routerFunction) {<br>        HttpHandler httpHandler = RouterFunctions.<em>toHttpHandler</em>(routerFunction);<br>        ReactorHttpHandlerAdapter adapter = new ReactorHttpHandlerAdapter(httpHandler);<br>        HttpServer server = HttpServer.<em>create</em>(&quot;localhost&quot;, Integer.<em>valueOf</em>(environment.getProperty(&quot;server.port&quot;)));<br>        server.newHandler(adapter);<br>        return server;<br>    }<br>}</pre><p>Classe Modelo User</p><pre>@Document(collection = &quot;user&quot;)<br>@TypeAlias(&quot;user&quot;)<br>public class User implements Serializable{</pre><pre>    private static final long <em>serialVersionUID </em>= 8860980640517255440L;</pre><pre>    @Id<br>    private String id;</pre><pre>    private String name;</pre><pre>    private String email;</pre><pre>    protected User (){}</pre><pre>    public User(String id, String name, String email) {<br>        this();<br>        this.id = id;<br>        this.name = name;<br>        this.email = email;<br>    }</pre><pre>    public String getId() {<br>        return id;<br>    }</pre><pre>    public String getName() {<br>        return name;<br>    }</pre><pre>    public String getEmail() {<br>        return email;<br>    }</pre><pre>}</pre><p>Repositório para User<br>Está sendo utilizado o ReactiveMongoRepository que contém as implementações reativas para as operações com banco de dados MongoDB.</p><pre>public interface UserRepository extends ReactiveMongoRepository&lt;User, String&gt; {}</pre><p>Handler para User<br>Mono e Flux são abstrações reativas pronto para implementar chamadas non-blocking, e a partir deles podemos criar expressões lambda para serem processadas no momento a resposta estiver sendo escrita ao Subscriber.</p><pre>@Service<br>public class UserHandler {</pre><pre>    private final UserRepository userRepository;</pre><pre>    @Autowired<br>    public UserHandler(UserRepository userRepository) {<br>        this.userRepository = userRepository;<br>    }</pre><pre>    public Mono&lt;ServerResponse&gt; findById(ServerRequest serverRequest){<br>        return ServerResponse.<em>ok</em>().body(this.userRepository.findById(serverRequest.pathVariable(&quot;id&quot;)), User.class);<br>    }</pre><pre>    public Mono&lt;ServerResponse&gt; findAll(ServerRequest serverRequest){<br>        return ServerResponse.<em>ok</em>().body(this.userRepository.findAll(), User.class);<br>    }</pre><pre>    public Mono&lt;ServerResponse&gt; save(ServerRequest serverRequest){<br>        Mono&lt;User&gt; userMono = serverRequest.bodyToMono(User.class);<br>        return ServerResponse.<em>ok</em>().body(this.userRepository.insert(userMono), User.class);<br>    }</pre><pre>    public Mono&lt;ServerResponse&gt; update(ServerRequest serverRequest){<br>        return ServerResponse.<em>ok</em>().body(this.userRepository.save(serverRequest.bodyToMono(User.class).block()), User.class);<br>    }</pre><pre>    public Mono&lt;ServerResponse&gt; delete(ServerRequest serverRequest) {<br>        return ServerResponse.<em>ok</em>().body(this.userRepository.deleteById(serverRequest.pathVariable(&quot;id&quot;)), Void.class);<br>    }<br>}</pre><p>Roteamento da API<br>Repare que o bom e velho @RestController não foi utilizado neste exemplo. Usamos uma nova abordagem de criar os endpoints baseados em roteamento, assim como outras linguagens e populares frameworks web já fazem hoje em dia (angularJS, Express e NodeJS por exemplo) o roteamento é adicionado ao ServletContainer que no caso é o Netty Server. Somente é iniciado a camada Network da aplicação que é ideal quando estamos trabalhando com microserviços assim expondo a API para ser consumida pelos clientes.</p><pre>@Configuration<br>public class Routes {</pre><pre>private static final String <em>PATH </em>= &quot;/api/user&quot;;<br>    private final UserHandler userHandler;</pre><pre>@Autowired<br>    public Routes(UserHandler userHandler) {<br>        this.userHandler = userHandler;<br>    }</pre><pre>@Bean<br>    public RouterFunction&lt;?&gt; routerFunction() {</pre><pre>return <em>nest</em>(<em>path</em>(<em>PATH</em>),<br>                <em>nest</em>(<em>accept</em>(MediaType.<em>APPLICATION_JSON</em>),<br>                        <em>route</em>(<em>GET</em>(&quot;/{id}&quot;), userHandler::findById)<br>                                .andRoute(<em>POST</em>(&quot;/&quot;), userHandler::save)<br>                                .andRoute(<em>PUT</em>(&quot;/{id}&quot;), userHandler::update)<br>                                .andRoute(<em>DELETE</em>(&quot;/{id}&quot;), userHandler::delete)<br>                                .andRoute(<em>GET</em>(&quot;/&quot;), userHandler::findAll)<br>                ));</pre><pre>}<br>}</pre><p>Para rodar, execute o comando:</p><blockquote>./gradlew clean build<br>java -jar build/libs/reactive-mongo-api.jar</blockquote><p>Se tudo ocorrer bem, sua aplicação estará rodando no endereço:</p><p><a href="http://localhost:9000/">http://localhost:9000</a></p><p>Contendo os serviços</p><p>GET <a href="http://localhost:9000/">http://localhost:9000</a>/v1/user<br>GET <a href="http://localhost:9000/">http://localhost:9000</a>/v1/user/{id}<br>POST <a href="http://localhost:9000/">http://localhost:9000</a>/v1/user<br>PUT <a href="http://localhost:9000/">http://localhost:9000</a>/v1/user/{id}<br>DELETE <a href="http://localhost:9000/">http://localhost:9000</a>/v1/user/{id}</p><p>É isso ai pessoal, este foi um exemplo bem simples, a idéia era mostrar as novidades qua estão por vir no Spring-Boot 2.0 e Spring-Framework 5.0 e uma abordagem inicial em programação funcional, reativa usando um Servlet Container subindo uma API como microservices.</p><h3>Referências:</h3><p><a href="https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0.0-M1-Release-Notes">Spring-Boot</a><br><a href="https://github.com/spring-projects/spring-framework/wiki/What%27s-New-in-the-Spring-Framework">Spring-Framework</a><br><a href="http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html">Oracle</a></p><p>Contatos<br>@<a href="https://medium.com/u/33bd97ada739">rbarbioni</a><br><a href="http://www.linkedin.com/in/rbarbioni">www.linkedin.com/in/rbarbioni</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96069ca1b652" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>