<?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 BilgehanYıldız on Medium]]></title>
        <description><![CDATA[Stories by BilgehanYıldız on Medium]]></description>
        <link>https://medium.com/@bilgehan.yildiz?source=rss-531df2b5f340------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*dmbNkD5D-u45r44go_cf0g.png</url>
            <title>Stories by BilgehanYıldız on Medium</title>
            <link>https://medium.com/@bilgehan.yildiz?source=rss-531df2b5f340------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 23:20:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bilgehan.yildiz/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[YAZILIM GUVENLIGI UZERINE DENEMELER 1]]></title>
            <link>https://medium.com/@bilgehan.yildiz/yazilim-guvenligi-uzerine-denemeler-1-27e5d636286c?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/27e5d636286c</guid>
            <category><![CDATA[yazılım-güvenliği]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Sun, 31 Mar 2024 16:08:31 GMT</pubDate>
            <atom:updated>2024-03-31T16:08:31.401Z</atom:updated>
            <content:encoded><![CDATA[<p>Yazdigimizin bir kodun yazilim guvenligini test etme acisindan kullanilan yontemlerden biride pentestlerdir.Pentest konusunda uzmanlasmis bir uzmandan bu destegi almak en iyi yontem olsada her zaman bu tarz bir uzmanla calisma sansina sahip olamayabiliriz.</p><p>Bu tarz profesyonel bir yardim alma sansimiz her zaman olmasada OWASP patternlerini takip ederek pek cok atak tipini onleme sansimiz bulunmaktadir.OWASP(The Open Web Application Security Project) Açık Web Uygulama Güvenliği Projesi, web uygulama güvenliği alanında ücretsiz olarak kullanılabilen makaleler, metodolojiler, belgeler, araçlar ve teknolojiler üreten bir topluluktur.</p><p>Bu yazimizda temel guvenlik ataklari simule etmemize yarayan burp suite uygulamasina da kullanarak brute force (kaba kuvvet) diye tabir edilen ve ozellikle kullanici ve adi sifreleri tahmin etmeye hedefleyen bir atak tipini burp suite yardimi ile uygulamamiz uzerinde deniyor olacagiz.</p><p>Kendiminde bu konularda bir uzman olmadigini ve sadece bir yazilimci olarak yazdigimiz kodun guvenligini arttirmak acisindan bu yaziyi yazdigimi da dipnot olarak belirtmek isterim.Imkanimiz varsa her zaman uzman bir pentestciden destek almak her zaman en iyi yoldur.</p><p>Gereken araclar</p><p>· Postman</p><p>· Burp suite community edition (<a href="https://portswigger.net/burp/communitydownload">https://portswigger.net/burp/communitydownload</a>)</p><p>· Herhangi bir ide intellij –eclipse olabilir</p><p>Ayrica yine portswigger site uzerinde pek cok atak tipini deneyip cozumlerini ogrenebileceginiz lablarda mevcut olup ,ozellikle yazilim guvenligine ilgili veya yeni baslayacak arkadaslar icin guzel bir referans noktasi olarak tavsiye edebilirim.</p><p><a href="https://portswigger.net/web-security/authentication/password-based/lab-broken-bruteforce-protection-ip-block">https://portswigger.net/web-security/authentication/password-based/lab-broken-bruteforce-protection-ip-block</a></p><p><a href="https://nordpass.com/most-common-passwords-list/">https://nordpass.com/most-common-passwords-list/</a></p><p>Oncelikle postman uygulamamizdan giden isteklerin burp suiten uzerinden gecebilmesi icin postman uygulamamiza custom proxy ayari yapalim</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Bt_xwPB55AevgKYWBDMSRQ.png" /></figure><p>2-)Burp suite uygulamamizi kurduktan sonra cift tiklayip acarak next diyelim ve default ayarlarla baslatalim</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*nUcUf4dcCsiV_SwNTB7euA.png" /></figure><p>3-)Spring boot ile basit bir login fonksiyonu lazim ve burada login sistemimizde default bir admin hesabi tanimlayalim</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*1fNLlAxcf7KR1oOwUIE74w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*2zD18Dia3fMoNByPzqo5Xg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*9URTJKLEdX9gWgUYngpMxg.png" /></figure><p>4-)Postmanden yaptigimiz istegimizin burp suite uzerinde http history kismindan gorebiliyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*euPv2Q742UZC3BogVY33Ug.png" /></figure><p>5-)Burp suite uzerinde http history kisminda istegimize gelerek sag tus yapip acilan menuden send to repeater diyerek mevcut istegi tekrar ettirebiliriz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*i-1CmU6rC9qrmSHlnSx_ow.png" /></figure><p>Send to repeater dedigimizde istek genel birlesenleri ile onumuze gelmektedir.Buradan istersek header veya parametreleri degistirip tekrar istek yollama yapabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*MpY_PCBgIvhdaBTeKLs3MA.png" /></figure><p>6-)Yine burp suite uzerinde kullanabilecegimiz bir diger ozellik ise intruder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*OfjI-yATcBSHq-hmkAbqYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*WTxVOIJ7szxY4cR-HZY7pg.png" /></figure><p>Intruder segmesine geldigimizde atak tipimiz</p><p>Sniper:Verdiginiz parameter listesini sirayla yeni bir istek olarak gonderir</p><p>ClusterBomb:Verdiginiz parameter listelerinin bir biri ile kombinasyonlarini olusturarak istek gonderir</p><p>7-)Biz Brute Force yani kaba kuvvet denemesi yapacagimiz icin cluster bomb seciyoruz</p><p>Ve Parametrelerimizi payload position kismina add diyerek listeden okunacak hale getiriyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*3FqCIVTC8kux8FcjGa3N8w.png" /></figure><p>Github veya baska bir kaynaktan edinebilecegimiz en sik kullanilan kullanici adi ve sifreler kopyalayip yapistiriyoruz</p><p><a href="https://github.com/danielmiessler/SecLists/blob/master/Usernames/cirt-default-usernames.txt">https://github.com/danielmiessler/SecLists/blob/master/Usernames/cirt-default-usernames.txt</a></p><p><a href="https://github.com/danielmiessler/SecLists/blob/master/Passwords/Common-Credentials/10k-most-common.txt">SecLists/Passwords/Common-Credentials/10k-most-common.txt at master · danielmiessler/SecLists</a></p><p>Ilk parametremize belli usernameler ekliyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/978/1*zzTKyw2OC26oBQ8io6Ha8w.png" /></figure><p>Ikinci parametremize ise belli passwordleri kopyaliyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*O0E1QQ3B_0Vo48fdaLrDXw.png" /></figure><p>8-)Baktigimiz zaman burp suite bizim icin sectigimiz username ve passwordlerden 88644 tane istek atarak deneme yapacak sekilde atagimizi hazirlamis oldu.Start attack diyerek atagimizi baslatiyoruz(Biz community edition kullandigimiz icin bir uyari veriyor ok diyip devam ediyoruz)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*o97qZAMffomtdFvPduZ_Yg.png" /></figure><p>9-)Ve atagimiz basladiginda atilan istek kombinasyonlarini ve sonuclarini gorebiliyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFBEiTeH4D38ExndyJ5JAQ.png" /></figure><p>10-)Asagidaki Kombinasyonunun</p><p>200 aldigini gormus olduk ve default kullanici adi ve sifre icin atagimiz basarili oldu.</p><p>{</p><p>“username”:”admin”,</p><p>“password”:”qwerty”</p><p>}</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FUxkwOckPvEmG5xP3GE6Ig.png" /></figure><p>10-)Guclu sifre kullanma ,ozellikle yuksek haklara sahip hesaplarin default kullanici adi ve sifrelerini degistirme,mfa kullanimi gibi yontemler ile brute force ataklarini engellemek mumkundur.Ve burp suite ile basit atak tiplerini kendi uygulamamiz icin deneyerek uygulama guvenligimizi arttirabiliriz.</p><p>Burp suite temel kullanimini aciklamaya yonelik bu yazimiz umarim faydali olur.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27e5d636286c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AXON FRAMEWORK KULLANARAK SPRING BOOT İLE SAGA PATTERN İMPLEMENTASYONU PART 2]]></title>
            <link>https://medium.com/@bilgehan.yildiz/axon-framework-kullanarak-spring-boot-i%CC%87le-saga-pattern-i%CC%87mplementasyonu-part-2-cc781b02eefd?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc781b02eefd</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[saga]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[axon-framework]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Sat, 23 Oct 2021 19:58:15 GMT</pubDate>
            <atom:updated>2021-10-23T19:58:15.245Z</atom:updated>
            <content:encoded><![CDATA[<p>Axon Framework ile örnek saga implementasyonu yapacağımız bu yazımızda saga,cqrs,axon frameworkle alakalı temel tanımlar için (ilk makale)aşağıdaki linkten açıklamaları okuyabilirsiniz.</p><p><a href="https://medium.com/@bilgehan.yildiz/axon-framework-kullanarak-spring-boot-i%CC%87le-cqrs-pattern-i%CC%87mplementasyonu-part-1-85fc5e15acd8">https://medium.com/@bilgehan.yildiz/axon-framework-kullanarak-spring-boot-i%CC%87le-cqrs-pattern-i%CC%87mplementasyonu-part-1-85fc5e15acd8</a></p><p>Öncelikle axona commandlar default paket adıyla register olmaktadır.Commandları microservisler arası taşıyabilmek için ya çekirdek bir jar yapıp commandları ordan referans olarak microservislere dağıtmak ya da microservisler arası paylaşılacak commandları aynı package ismiyle olacak şekilde microservislerimizde oluşturmamız gerekmektedir.Üçüncü ise seçenek ise commandhandlerlar oluşurken commandName vermektir.</p><pre>@CommandHandler(commandName = &quot;DeleteTestEntityCommand&quot;)</pre><pre>public void deleteTestAggregate(DeleteTestEntityCommand command)</pre><pre>{</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*d3ZSLN2PyYMg9mn08v-Bxg.png" /></figure><p>Örneğimizde iki adet microservisimiz olacak.Test nesnemiz yaratıldığında (test-writer-microservisimizden) bu bir sonraki akışımızda order microservisimize bir event göndererek order yaratılmasını sağlayacak.Order cancel edildiğinde ise test entitymizinde cancel olması sağlanacak.</p><p>Bu akış tabiki daha fazla microservis bağlantılı senaryo ile desteklenebilir.</p><p>Buradaki iş akışınıda axon frameworkünün sağladığı yetenekleri kullanacağız</p><p>Saga aslında özel bir event listener türüdür.Bazı işlemler çok uzun saatlerce vs sürebilirken bazı işlemler saniyenin altında tamamlanabilir.Saga tek bir iş akışını yönetmekten sorumludur.Bunuda iş akışını bir sonraki state taşıyarak veya hata durumunda compensation(telafi edici) aksiyonları alarak sağlar.Saganın eventler tarafından tetiklenen bir başlangıç ve bitiş noktası vardır.</p><p>Tek bir Saga instance tek bir business transacitonı yönetmekten sorumludur</p><p>@SagaEventHandler:Sagadaki event listenerları belirlemek için kullanılan anatosyon</p><p>@StartSaga:Sagadaki bir event handler eğer işlemin başlangıç noktasını gösteriyorsa bu anatosyon sagaeventhandlera ek olarak eklenmelidir</p><p>@EndSaga(Anatosyon olarak kullanılır alternatifi kod içerisinde SagaLifecycle.end()):Saga instance yaşam döngüsünü sonlandırmak için kullanılır</p><p>associationProperty:Gelen eventin İlgili sagaları bulmak için gelen eventteki özelliğin adıdır.</p><p>@SagaEventHandler(associationProperty = “id”)</p><p>SagaLifecycle.associateWith:Bir saga birden fazla domain de olan bir transaction yönetimi yapıyor ise sağanın bu domainlerle ilişkisini kurabilmesi için gerekli olan ilişki yönetimin kısmını yapar.</p><pre>SagaLifecycle.<em>associateWith</em>(&quot;orderId&quot;, orderId);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*JmBqIW4R8B_VVG0xN8x2ZQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/282/1*M_Ujk_GuKc50OOuwG9g4DQ.png" /></figure><p>CQRS örneğinde olduğu gibi Aggregate,Command ve Event Tanımlarımızı yapıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*2HlH2E77BVa_B2P43GhanQ.png" /></figure><blockquote>Örnek Command sınıfımız burada önemli olan @TargetAggregateIdentifier belirteci</blockquote><blockquote><strong>Command:</strong>Veriyi oluşturan(insert) ya da veriyi manipüle eden(update,delete) işlemlerine command denir. Commandlar gelecekte reddebilecek veya kabul edilebilecek bir isteği temsil eder.</blockquote><pre>import org.axonframework.modelling.command.TargetAggregateIdentifier;<br><br><br><br>public class CreateTestEntityCommand {<br><br>    @TargetAggregateIdentifier<br><br>    public final String id;<br><br>    public final String name;<br><br>    public final String info;<br><br><br><br><br><br>    public CreateTestEntityCommand(String id,String name)<br><br>    {<br><br>        this.id=id;<br><br>        this.name=name;<br><br>        this.info=&quot;Test Entity creation will be requested&quot;;<br><br>    }<br><br><br><br>}</pre><blockquote>Örnek Event sınıfımız</blockquote><blockquote><strong>Events:</strong>Zaten olmuş ve geri alınamayacak (immutable) bir geçmişi temsil eder</blockquote><pre>public class TestEntityCreatedEvent {</pre><pre>    public final String id;</pre><pre>    public final String name;</pre><pre>    public final String info;</pre><pre>    public TestEntityCreatedEvent(String id,String name)</pre><pre>    {</pre><pre>        this.id=id;</pre><pre>        this.name=name;</pre><pre>        this.info=&quot;Test Entity created Event&quot;;</pre><pre>    }</pre><pre>}</pre><blockquote>Örnek Aggregate sınıfımız</blockquote><blockquote><strong>Aggregate:</strong>Her zaman tutarlı bir durumda tutulan varlık/varlıklar grubudur</blockquote><pre>@Aggregate</pre><pre>public class TestAggregate {</pre><pre>    @AggregateIdentifier</pre><pre>    private String id;</pre><pre>    private String name;</pre><pre>    private String info;</pre><pre>    private int status;</pre><pre>    public TestAggregate(){}</pre><pre>    @CommandHandler</pre><pre>    public TestAggregate(CreateTestEntityCommand command)</pre><pre>    {</pre><pre>        AggregateLifecycle.<em>apply</em>(new TestEntityCreatedEvent(command.id,command.name));</pre><pre>    }</pre><pre>    @EventSourcingHandler</pre><pre>    protected void on(TestEntityCreatedEvent testEntityCreatedEvent){</pre><pre>        this.id=testEntityCreatedEvent.id;</pre><pre>        this.name=testEntityCreatedEvent.name;</pre><pre>        this.info=testEntityCreatedEvent.info;</pre><pre>    }</pre><pre>    @CommandHandler</pre><pre>    public void updateTestAggregate(UpdateTestEntityCommand command)</pre><pre>    {</pre><pre>        AggregateLifecycle.<em>apply</em>(new TestEntityUpdatedEvent(command.id,command.status));</pre><pre>    }</pre><pre>    @EventSourcingHandler</pre><pre>    protected void on(TestEntityUpdatedEvent testEntityUpdatedEvent){</pre><pre>        this.id=testEntityUpdatedEvent.id;</pre><pre>        this.status=testEntityUpdatedEvent.status;</pre><pre>        this.info=testEntityUpdatedEvent.info;</pre><pre>    }</pre><pre>    @CommandHandler(commandName = &quot;DeleteTestEntityCommand&quot;)</pre><pre>    public void deleteTestAggregate(DeleteTestEntityCommand command)</pre><pre>    {</pre><pre>        AggregateLifecycle.<em>apply</em>(new TestEntityDeletedEvent(command.id,command.status));</pre><pre>    }</pre><pre>    @EventSourcingHandler</pre><pre>    protected void on(TestEntityDeletedEvent testEntityDeletedEvent){</pre><pre>        this.id=testEntityDeletedEvent.id;</pre><pre>        this.status=testEntityDeletedEvent.status;</pre><pre>        this.info=testEntityDeletedEvent.info;</pre><pre>    }</pre><pre>    @CommandHandler</pre><pre>    public void compensateTestAggregate(CompensateTestEntityCommand command)</pre><pre>    {</pre><pre>        AggregateLifecycle.<em>apply</em>(new TestEntityCompensatedEvent(command.id,command.status));</pre><pre>    }</pre><pre>    @EventSourcingHandler</pre><pre>    protected void on(TestEntityCompensatedEvent testEntityCompensatedEvent){</pre><pre>        this.id=testEntityCompensatedEvent.id;</pre><pre>        this.status=testEntityCompensatedEvent.status;</pre><pre>    }</pre><pre>}</pre><blockquote>Servis katmanından örnek commandgateway kullanarak event akışlarını başlatma</blockquote><pre>@Service</pre><pre>public class TestServiceImpl {</pre><pre>    private final CommandGateway commandGateway;</pre><pre>    private final EventStore eventStore;</pre><pre>    public TestServiceImpl(CommandGateway commandGateway,EventStore eventStore) {</pre><pre>        this.commandGateway = commandGateway;</pre><pre>        this.eventStore=eventStore;</pre><pre>    }</pre><pre>    public String createTest(String id)</pre><pre>    {</pre><pre>        try{</pre><pre>            String idtoEvent= UUID.<em>randomUUID</em>().toString();</pre><pre>        CompletableFuture&lt;Object&gt; result= commandGateway.send(new CreateTestEntityCommand(id,&quot;Bilgehan&quot;));</pre><pre>         return idtoEvent;</pre><pre>        }</pre><pre>        catch (Exception ex)</pre><pre>        {</pre><pre>            System.<em>out</em>.println(&quot;Command error&quot;);</pre><pre>        }</pre><pre>        return &quot;&quot;;</pre><pre>    }</pre><pre>…………………..</pre><pre>}</pre><blockquote><strong>Handlers:</strong>Uygulama üzerinde yapılacak her command ve query isteklerini işleyecek yapılara denir.</blockquote><pre>@Component</pre><pre>public class TestProjection {</pre><pre>    @Autowired</pre><pre>    private  TestRepository testRepository;</pre><pre>    @EventHandler</pre><pre>    public void on(TestEntityCreatedEvent event) {</pre><pre>       System.<em>out</em>.println(&quot;Test entity yaratıldı&quot;+event.id);</pre><pre>        TestEntity testEntity=new TestEntity();</pre><pre>        testEntity.setId(event.id);</pre><pre>        testEntity.setName(event.name);</pre><pre>        testEntity.setInfo(event.info);</pre><pre>        testRepository.save(testEntity);</pre><pre>    }</pre><pre>    @EventHandler</pre><pre>    public void on(TestEntityUpdatedEvent event) {</pre><pre>        System.<em>out</em>.println(&quot;Test entity update edildi&quot;+event.id);</pre><pre>       Optional&lt;TestEntity&gt; testEntityOpt= testRepository.findById(event.id);</pre><pre>        if(testEntityOpt.isPresent())</pre><pre>        {</pre><pre>            TestEntity testEntity=   testEntityOpt.get();</pre><pre>            testEntity.setStatus(event.status);</pre><pre>            testEntity.setInfo(event.info+event.id);</pre><pre>            testRepository.save(testEntity);</pre><pre>        }</pre><pre>    }</pre><pre>    @EventHandler</pre><pre>    public void on(TestEntityCompensatedEvent event) {</pre><pre>        System.<em>out</em>.println(&quot;Test entity cancel edildi&quot;+event.id);</pre><pre>        Optional&lt;TestEntity&gt; testEntityOpt= testRepository.findById(event.id);</pre><pre>        if(testEntityOpt.isPresent())</pre><pre>        {</pre><pre>            TestEntity entity=testEntityOpt.get();</pre><pre>            entity.setStatus(event.status);</pre><pre>            testRepository.save(entity);</pre><pre>        }</pre><pre>    }</pre><p>Burada saga kordinatorı taşıyacak olan com.example.saga(TestWriter servisimiz içinde) SagaEventHandlerlarımızı tanımlıyoruz</p><p>Örneğimizde TestEntityCreatedEvent oluşması bizim için sağanın başlangıç noktası o yüzden burayı @StartSaga şeklinde işaretliyoruz.</p><p>StartSagadan CreateOrderCommand göndereceğiz.Bu ise diğer microservisimiz olan ordersaganın aggregate kısmına düşecek.OrderCreated olduğu zaman tekrar sagamızdaki ikinci adıma gelecek buradan sonra akış devamı ve saganın bitirilmesi gibi durumlar kodlanabilir</p><blockquote>Örnekte sadece OrderSaga servisinden birde tersine alma akışı gönderielerek geri alma işlemlerininde tetiklenme örneği</blockquote><pre>spring.application.name=test-writer-service)</pre><pre>package com.example.saga.manager;</pre><pre>import com.example.saga.command.CompensateTestEntityCommand;</pre><pre>import com.example.saga.command.CreateOrderCommand;</pre><pre>import com.example.saga.events.OrderCompensatedEvent;</pre><pre>import com.example.saga.events.OrderCreatedEvent;</pre><pre>import com.example.saga.events.TestEntityCreatedEvent;</pre><pre>import org.axonframework.commandhandling.gateway.CommandGateway;</pre><pre>import org.axonframework.modelling.saga.EndSaga;</pre><pre>import org.axonframework.modelling.saga.SagaEventHandler;</pre><pre>import org.axonframework.modelling.saga.SagaLifecycle;</pre><pre>import org.axonframework.modelling.saga.StartSaga;</pre><pre>import org.axonframework.spring.stereotype.Saga;</pre><pre>import org.springframework.beans.factory.annotation.Autowired;</pre><pre>import java.util.UUID;</pre><pre>@Saga</pre><pre>public class TestManagementSaga   {</pre><pre>    @Autowired</pre><pre>    private transient CommandGateway commandGateway;</pre><pre>//Saga ilk adım</pre><pre>    @StartSaga</pre><pre>    @SagaEventHandler(associationProperty = &quot;id&quot;)</pre><pre>    public void handle(TestEntityCreatedEvent testEntityCreatedEvent){</pre><pre>        String orderId = UUID.<em>randomUUID</em>().toString();</pre><pre>        System.<em>out</em>.println(&quot;Saga invoked&quot;);</pre><pre>        <em>//associate Saga</em></pre><pre><em>        </em>SagaLifecycle.<em>associateWith</em>(&quot;orderId&quot;, orderId);</pre><pre>        commandGateway.send(new CreateOrderCommand(orderId,&quot;Sagadan order create&quot;, testEntityCreatedEvent.id))</pre><pre>                .exceptionally(throwable -&gt; {</pre><pre>                   return  commandGateway.send(new CompensateTestEntityCommand(testEntityCreatedEvent.id,2)); })</pre><pre>        ;</pre><pre>        System.<em>out</em>.println(&quot;test id&quot; + testEntityCreatedEvent.id);</pre><pre>    }</pre><pre>//Saga ikinci adım</pre><pre>    @SagaEventHandler(associationProperty = &quot;orderId&quot;)</pre><pre>    public void handle(OrderCreatedEvent orderCreatedEvent){</pre><pre>        System.<em>out</em>.println(&quot;Saga continued&quot;);</pre><pre>//TODO başarı durumuna göre endSaga buradada çağıralabilir</pre><pre>    }</pre><pre>//Saga rollback örnek</pre><pre>    @SagaEventHandler(associationProperty = &quot;orderId&quot;)</pre><pre>    public void on(OrderCompensatedEvent event) {</pre><pre>        System.<em>out</em>.println(&quot;order canceled&quot;);</pre><pre>        commandGateway.send(new CompensateTestEntityCommand(event.testId,2));</pre><pre>        endSaga();</pre><pre>    }</pre><pre>    @EndSaga</pre><pre>    private void endSaga() {</pre><pre>        System.<em>out</em>.println(&quot;ENDING SAGA&quot;);</pre><pre>    }}</pre><p>Kodların tamamına github üzerinden ulaşabilirsiniz</p><p><a href="https://github.com/BilgehanYildiz/axonframeworksaga">https://github.com/BilgehanYildiz/axonframeworksaga</a></p><p>İki adet proje vardır.ordersaga ilk projenin içine zip olarak eklenmiştir</p><p>Ordersaga projesinin altında diğer projedeki paket adlarıyla defaultta aynı olması için ilk projeye göre paket yapısı oluşturulmuştur.Bunlar ortak bir jarın içine çekilip ordan microservislere referans olarak verilebilir.CommandHandlerlara commandname ile alias verilerek ayarlanabilir veya bu sekilde ortak bir paket adı yapısı oluşturulup classların kopyaları projeler arası oluşturulabilir(Microservisler arası fiziksel bağımlılık yapacak bir jar daha oluşturulmak istenmiyorsa).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*P4ibd0B0EKnDhxtlNy--Eg.png" /></figure><p>Kaynakça</p><p><a href="https://github.com/xstefank/axon-service/blob/master/order-service/src/main/java/org/learn/axonframework/orderservice/saga/OrderManagementSaga.java">https://github.com/xstefank/axon-service/blob/master/order-service/src/main/java/org/learn/axonframework/orderservice/saga/OrderManagementSaga.java</a></p><p><a href="https://docs.axoniq.io/reference-guide/v/3.1/part-ii-domain-logic/sagas">https://docs.axoniq.io/reference-guide/v/3.1/part-ii-domain-logic/sagas</a></p><p><a href="https://progressivecoder.com/saga-pattern-implementation-axon-spring-boot-part-2/">https://progressivecoder.com/saga-pattern-implementation-axon-spring-boot-part-2/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc781b02eefd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AXON FRAMEWORK KULLANARAK SPRING BOOT İLE CQRS PATTERN İMPLEMENTASYONU PART 1]]></title>
            <link>https://medium.com/@bilgehan.yildiz/axon-framework-kullanarak-spring-boot-i%CC%87le-cqrs-pattern-i%CC%87mplementasyonu-part-1-85fc5e15acd8?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/85fc5e15acd8</guid>
            <category><![CDATA[saga]]></category>
            <category><![CDATA[axon-framework]]></category>
            <category><![CDATA[cqrs]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 09:56:55 GMT</pubDate>
            <atom:updated>2021-10-17T09:56:55.661Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu konuya ait İlk makalede CQRS ve SAGA Patternlerinin açıklamalarını bulabilirsiniz.Ayrıca axon frameworkle ilgili temel kavramlara ait açıklamalarıda bulunabilir.Son olarak spring boot ve axon frameworkle örnek bir cqrs implementasyonunu yine part 1 makalesinde okuyabilirsiniz.Saga implementasyonu part2 makalesinin içeriğinde yer alacaktır.</p><p><strong>CQRS(Command Query Responsibility Segregation) NEDİR?</strong></p><p><strong>Command:</strong>Veriyi oluşturan(insert) ya da veriyi manipüle eden(update,delete) işlemlerine command denir. Commandlar gelecekte reddebilecek veya kabul edilebilecek bir isteği temsil eder.</p><p><strong>Query</strong>:Veriyi okumak (select) için yapılan işlemlere query denir.</p><p>CQRS ise bu iki işlem tipini birbirinden ayrıştırarak farklı data modelleriyle gerçekleştirme prensibine denir.</p><p><strong>Handlers:</strong>Uygulama üzerinde yapılacak her command ve query isteklerini işleyecek yapılara denir.</p><p><strong>Aggregate:</strong>Her zaman tutarlı bir durumda tutulan varlık/varlıklar grubudur.</p><p>CQRS tabanlı işlemlerde aggregateler değişimin başladığı yerdir.Kendi başlarına domain driven desingde nesneler bir araya gelerek iş akışını oluşturmamıza olanak sağlar.</p><p>Aggregate bir jpaentitysi değil bir business entity veya entity kümesi olarak düşünebiliriz.</p><p><strong>Events:</strong>Zaten olmuş ve geri alınamayacak (immutable) bir geçmişi temsil eder</p><p>Bir eventin birden fazla tüketicisi olabilir.Ancak commandlar sadece bir tanesine yöneliktir.</p><p>CQRS çok fazla paydaşın olduğu verilerde geliştirme aşamalarını farklı takımlara bölmemize olanak sağlayarak her paydaşın kendi logici üzeirnde çalışmasına olanak sağlayan bir yaklaşımdır.</p><p><strong>Domain Driven Design:</strong>Wikipedia daki tanımı<strong> ‘</strong>Yazılım kodunun yapısının ve dilinin iş alanıyla eşleşmesi gerektiği kavramıdır. Örneğin, bir yazılım kredi başvurularını işliyorsa, LoanApplication ve Customer gibi sınıflara ve AcceptOffer ve Withdraw gibi yöntemlere sahip olabilir. DDD, uygulamayı gelişen bir modele bağlar.’</p><p><strong>SAGA PATTERN NEDİR?</strong></p><p>Microservis mimarinizde her microservis için ayrı bir database kullanıyorsanız bunun sonucu olarak özellikle long running işlemlerde transaction yöntemi olarak saga pattern implementasyonu yapmanız gerekecektir.</p><p>Saga pattern dağıtık mimarilerde veriler arası tutarlılık (consistency) sağlamak amacıyla bir hata yönetim patterni olarak karşımıza çıkmaktadır.</p><p>Saga Pattern implementasyonunda her local transaction bir event veya message başlatarak bir sonraki transactionın başlatılmasından sorumludur.</p><p>Hata durumu oluştuğunda saga çözümü sayesinde yazılmış olan compensation servisleri ile yapılmış transactionların rollback olması sağlanır.</p><p>Ancak unutulmaması gereken önemli bir nokta saga çözümleri dirty transaction oluşmasına açık bir konudur.</p><p>İki tip Saga Pattern yöntemi vardır.</p><p>Choregrapy Based Saga:Her bir transaction kendin sonraki transaction ve compensatiton senaryolarını tetiklemekten sorumludur.</p><p>Orchestaration Based Saga:Saga pattern için gerekli transaciton akışını yöneten bir koordinatör bulunmaktadır</p><p>Burada orchestration Based Saga patternini sağlamak amacıyla axon framework kullanıyor olacağız.</p><p><strong>AXON FRAMEWORK NEDİR?</strong></p><p>Axon framework domain driven design tekniklerini kullanarak cqrs,saga gibi çözümleri uygulamaya yarayan java based bir microservis frameworküdür.</p><p>Axon frameworkünün bir diğer artısı spring ekosistemi ile uyumlu çalışabilen bir framework olmasıdır.</p><p>Öncelikle axon sitesinden</p><p>AxonQuickStart dosyasını indirerek kurulumunu gerçekleştiriyoruz</p><p>Axon Framework ek olarak AxonServer birleşenide bulunmaktadır.AxonServer axon framework entegre kullanabildiğimiz gibi ayrı olarak da kullanabiliyoruz.</p><p>Axon Server sayesinde event,command mesajların birbiri arasında yönlendirilmesi,monitoring security gibi işlemleri daha hızlı yapabiliyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*oivhfP7X7-_ST8-grX2afQ.png" /></figure><p><a href="https://docs.axoniq.io/reference-guide/axon-server-introduction">https://docs.axoniq.io/reference-guide/axon-server-introduction</a></p><p>Axon Server container üzerinden kullanılabileceği gibi executive jar olarak da indirip start edebilirsiniz</p><p><a href="https://docs.axoniq.io/reference-guide/axon-server/installation/local-installation/axon-server-se">https://docs.axoniq.io/reference-guide/axon-server/installation/local-installation/axon-server-se</a></p><p>java -jar C:\AxonServer-4.5.7\axonserver.jar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*LHn5--j40PM0Vnu-wBsphQ.png" /></figure><p>Default olarak aşağıdaki porttan axon server management console erişilebilir</p><p><a href="http://localhost:8024/">http://localhost:8024/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*xp7OQcbjYyO-9mp-5CoUPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*enW59hWt94WM-qsn4WDFOQ.png" /></figure><p>Axon Terimleri:</p><p>· <strong>AggreagateLifeCycle:</strong>Bir aggreagete üzerinden olay(event)yayınlamak için.Apply kullanılır.Bir command execyte edilerken uygulamanın gerikalanına yeni bir event oluşturulduğunu bildirir.</p><p>· <strong>CommandGateway</strong>:Axonun komut işleme birleşenlerine yönelik arayüzüdür.Command gateway ile gönderilen komutların sonuçları beklenebilir.</p><p>· QueryGateway:</p><p>CQRS için axonframework çalışma mantığı:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/445/1*4sRU2knG7C9gL_ILUshOqg.png" /></figure><p>İlk hatamız</p><blockquote>Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Table “TOKEN_ENTRY” not found; SQL statement:</blockquote><blockquote>select tokenentry0_.processor_name as processo1_3_0_, tokenentry0_.segment as segment2_3_0_, tokenentry0_.owner as owner3_3_0_, tokenentry0_.timestamp as timestam4_3_0_, tokenentry0_.token as token5_3_0_, tokenentry0_.token_type as token_ty6_3_0_ from token_entry tokenentry0_ where tokenentry0_.processor_name=? and tokenentry0_.segment=? [42102–200]</blockquote><blockquote>at org.h2.message.DbException.getJdbcSQLException(DbException.java:453) ~[h2–1.4.200.jar:1.4.200]</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/183/1*wwJetzC8ljLo9eQG7KU7Zg.png" /></figure><p>Axonframework event yapılarını takip edebilmek için database üzerinde tablolara ihtiyaç duymaktadır.Bu tablolar bulunmadığı takdirde yukarıdaki gibi hata olacaktır</p><p>Sample için bu hatayı alırsanız hızlı çözüm adına application.properties içerisine aşağıdaki ayarı ekleyerek ilerleyebilirsiniz.</p><p>spring.jpa.hibernate.ddl-auto=update duruma göre create de diyebiliriz veya tabloları manuel oluşturmamız gereklidir</p><p>AXON tarafından oluşturulan tablolar</p><p><strong>SAGA_ENTRY</strong> :serialize edilmiş saga kayıtlarının tutulduğu tablo</p><p><strong>ASSOCATION_VALUE_ENTRY</strong>:</p><p><strong>TOKEN_ENTRY</strong>:</p><p>TrackingEventProcessor TrackingTokenı işlenen eventlerin durumunu izleme için kullanılır</p><p>TrackingToken eventstream üzerindeki eventin pozisyonunu temsil eder.</p><p>Tracking Tokenlar tokenstoreda saklanır.</p><p>TokenStore implementasyonu için jpa,jdbc vs gibi farklı implementasyonlarla saklanabilir</p><p>TokenEntry tablosu:Axon Framework her processing group için bir token tutar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*kseh1MqDS3HikSUI2IUsYw.png" /></figure><p>Axon Terimleri:</p><p>· <strong>AggregateIdentifier:</strong> string,UUID ve primitive olmayan numericler kullanılabilir, örnek int seklinde identifier sequence hatasına yol açmaktadır.</p><p>OUT_OF_RANGE: [AXONIQ-2000] Invalid sequence number: 0</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*iS4KN5aRTq64G2RnWwIpmg.png" /></figure><p><a href="https://discuss.axoniq.io/t/re-axonframework-re-differences-between-eventhandler-and-eventsourcinghandler/2433/2">https://discuss.axoniq.io/t/re-axonframework-re-differences-between-eventhandler-and-eventsourcinghandler/2433/2</a></p><p>· <strong>EventSourcingHandler: Gönderilen eventin işleyicisini belirtmek için axon anotasyonu</strong></p><p>· <strong>CommandHandler:Gönderilen komutun işleyicisini belirtmek için axon anotasyonu</strong></p><p>· <strong>Projector sınıfları:Axon frameworkünde her bir event geldiği zaman db işlemlerini yapacak sınıfları tanımlamak için oluşturulan keywordün(mantıksal bir terminoloji)</strong></p><p>· <strong>EventHandler:Yaratılmış event geldikten sonra projector sınıfı içerisinde eventleri dinlemek için oluşturulan methodların tepesine konulan axon anotasyonu</strong></p><p>Öncelikle command ve event sınıflarımızı oluşturalım</p><p>Command classımızdaki @TargetAggregateIdentifier Aggregateimizin idsi için gereklidir.</p><pre>import org.axonframework.modelling.command.TargetAggregateIdentifier;</pre><pre>public class CreateTestEntityCommand {</pre><pre>    @TargetAggregateIdentifier</pre><pre>    public final String id;</pre><pre>    public final String name;</pre><pre>    public final String info;</pre><pre>    public final int testid;</pre><pre>    public CreateTestEntityCommand(String id,String name,int testid)</pre><pre>    {</pre><pre>        this.id=id;</pre><pre>        this.name=name;</pre><pre>        this.testid=testid;</pre><pre>        this.info=&quot;Test Entity creation will be requested&quot;;</pre><pre>    }</pre><pre>}</pre><p>Event classımız</p><pre>public class TestEntityCreatedEvent {<br> public final String id;<br> public final String name;<br> public final String info;<br> public final int testid;<br> <br> public TestEntityCreatedEvent(String id,String name,int testid)<br> {<br> this.id=id;<br> this.name=name;<br> this.info=”Test Entity created Event”;<br> this.testid=testid;<br> }<br> <br> }</pre><p>Genel pattern olarak command isimleri yapılacak aksiyon(create,update vs)+Command son ekiyle biter</p><p>Eventler ise geçmiş zaman aksiyonu(Created,Updated) +Event son ekiyle biter</p><p>Aggregate classımız</p><p>Not: AggregateIdentifier olarak seçilecek alan command.gatewayden gönderilerken kullanılacak event id olmalı aksi takdirde aggregate not found hatası alınır.Genel örneklere bakıldığında aggregateidentifier ile jpa identifier aynı olduğunu görülmektedir.Ancak aşağıdaki örneklerde ikisi farklı kurulacağını göstermek için jpadaki id ile aggreagateidentifierlar ayrı tutulmuştur.AggreagaeIdentifier String,UUID veya Integer gibi (primitve olmayan) sayısal değerler kullanılabilir.</p><pre>@Aggregate<br><br>public class TestAggregate {<br><br>    @AggregateIdentifier<br><br>    private String id;<br><br>    private String name;<br><br>    private String info;<br><br>    private int status;<br><br>    private  int testid;<br><br><br><br>    public TestAggregate(){}<br><br><br><br>    @CommandHandler<br><br>    public TestAggregate(CreateTestEntityCommand command)<br><br>    {<br><br>        AggregateLifecycle.<em>apply</em>(new TestEntityCreatedEvent(command.id,command.name,command.testid));<br><br>    }<br><br><br><br>    @EventSourcingHandler<br><br>    protected void on(TestEntityCreatedEvent testEntityCreatedEvent){<br><br><br><br>        this.id=testEntityCreatedEvent.id;<br><br>        this.name=testEntityCreatedEvent.name;<br><br>        this.info=testEntityCreatedEvent.info;<br><br>    }<br><br><br><br>    @CommandHandler<br><br>    public void updateTestAggregate(UpdateTestEntityCommand command)<br><br>    {<br><br>        AggregateLifecycle.<em>apply</em>(new TestEntityUpdatedEvent(command.id,command.status,command.testid));<br><br>    }<br><br><br><br>    @EventSourcingHandler<br><br>    protected void on(TestEntityUpdatedEvent testEntityUpdatedEvent){<br><br><br><br>        this.id=testEntityUpdatedEvent.id;<br><br>        this.status=testEntityUpdatedEvent.status;<br><br>        this.info=testEntityUpdatedEvent.info;<br><br>        this.testid=testEntityUpdatedEvent.testid;<br><br>    }<br><br><br><br><br><br>}</pre><p>Bir servis katmanızda artık commandgateway sayesinde komutlarımızı gönderebiliyoruz.</p><pre>@Service<br><br>public class TestServiceImpl {<br><br>    private final CommandGateway commandGateway;<br><br><br><br>    private final EventStore eventStore;<br><br><br><br><br><br>    public TestServiceImpl(CommandGateway commandGateway,EventStore eventStore) {<br><br>        this.commandGateway = commandGateway;<br><br>        this.eventStore=eventStore;<br><br>    }<br><br><br><br><br><br>public String createTest(int id)<br><br>{<br><br>    try{<br><br>        String idtoEvent= UUID.<em>randomUUID</em>().toString();<br><br>    CompletableFuture&lt;Object&gt; result= commandGateway.send(new CreateTestEntityCommand(idtoEvent,&quot;Bilgehan&quot;,id));<br><br>     return idtoEvent;<br><br>    }<br><br>    catch (Exception ex)<br><br>    {<br><br>        System.<em>out</em>.println(&quot;Command error&quot;);<br><br>    }<br><br>    return &quot;&quot;;<br><br>}</pre><pre>….</pre><pre>}</pre><p>Projection classımızdaki handler sayesinde herevent geldiğinde(commandgatewayden send edilen eventler) ona göre aksiyon alabiliyoruz</p><pre>@Component<br> public class TestProjection {<br> <br>     @Autowired<br>     private  TestRepository testRepository;<br> <br>     @EventHandler<br>     public void on(TestEntityCreatedEvent event) {<br>        System.<em>out</em>.println(&quot;Test entity yaratıldı&quot;+event.id);<br>         TestEntity testEntity=new TestEntity();<br>         testEntity.setId(event.testid);<br>         testEntity.setEventid(event.id);<br>         testEntity.setName(event.name);<br>         testEntity.setInfo(event.info);<br> <br>         testRepository.save(testEntity);<br>     }</pre><pre>…..</pre><pre>}</pre><p>Dipnot: TrackingEventProcessorConfiguration ve TokenStore ayarları yapılmazsa default olarak inmemory mantığında eventhandler çalışıyor yani uygulama her yeniden başladığında aynı eventlerin tekrar okunmasına neden oluyor o yüzden bir axon config oluşturarak bu ayarları yapıyor olmakta fayda bulunmaktadır.</p><pre>@Configuration<br> public class AxonConfig {<br> <br> @Bean<br> EventSourcingRepository&lt;TestAggregate&gt; testAggregateEventSourcingRepository(EventStore eventStore)<br> {<br> EventSourcingRepository&lt;TestAggregate&gt; repository= EventSourcingRepository.<em>builder</em>(TestAggregate.class).eventStore(eventStore).build();<br> return repository;<br> }<br> <br> @Bean<br> public TokenStore tokenStore(Serializer serializer, EntityManagerProvider entityManagerProvider) {<br> return JpaTokenStore.<em>builder</em>()<br> .entityManagerProvider(entityManagerProvider)<br> .serializer(serializer)<br> .build();<br> }<br> <br> <br> @Autowired<br> public void configureProcessors(EventProcessingConfigurer eventProcessingConfigurer) {<br> TrackingEventProcessorConfiguration tepConfig = TrackingEventProcessorConfiguration.<em>forSingleThreadedProcessing</em>().andInitialTrackingToken(StreamableMessageSource::createHeadToken);<br> eventProcessingConfigurer.registerTrackingEventProcessorConfiguration(config -&gt; tepConfig);<br> }<br> <br> }</pre><p>Yazma kısmı CORS sin CRS kısmını axonla yukarıdaki şekilde gerçekleştirebildik</p><p>CRS kısmı için akış</p><p>CommandGateway(Send) →Aggregate →CommandHandler(Command) →EventSourcingHandler(Event) →EventHandler →Db</p><p>Simdi QRS kısmının axonla nasıl olacağına bakalım.</p><p>Sorgulamada parametre geçişi için bir adet query sınıfı oluşturuyoruz</p><pre>public class FindTestEntityQuery {<br> private String eventid;<br> <br> public FindTestEntityQuery(String eventid)<br> {<br> this.setEventid(eventid);<br> }<br> <br> public String getEventid() {<br> return eventid;<br> }<br> <br> public void setEventid(String eventid) {<br> this.eventid = eventid;<br> }<br> }</pre><p>QueryHandler ise artık sorgulamalara düşen eventler için kullandığımız anotasyon oluyor</p><pre>@Component<br> public class TestProjection {<br> <br> @Autowired<br> private TestRepository testRepository;<br> <br> @QueryHandler<br> public TestEntity handle(FindTestEntityQuery query) {<br> System.<em>out</em>.println(“query: {}”+query);<br> return this.testRepository.findByEventID(query.getEventid());<br> }<br> }</pre><p>Son olarak QueryGateway ile sorgularımızı yönlendirebiliyoruz</p><pre>@Service<br> public class TestService {<br> private final QueryGateway queryGateway;<br> private final EventStore eventStore;<br> <br> public TestService(QueryGateway queryGateway,EventStore eventStore)<br> {<br> this.queryGateway=queryGateway;<br> this.eventStore=eventStore;<br> }<br> <br> public CompletableFuture&lt;TestEntity&gt; findById(String eventid) {<br> return this.queryGateway.query(<br> new FindTestEntityQuery(eventid),<br> ResponseTypes.<em>instanceOf</em>(TestEntity.class)<br> );<br> }<br> <br> public List&lt;Object&gt; listEventsForTestEntity(String eventid) {<br> return this.eventStore<br> .readEvents(eventid)<br> .asStream()<br> .map(Message::getPayload)<br> .collect(Collectors.<em>toList</em>());<br> }<br> }</pre><p>CQRS deki QRS akışı</p><p>QueryGateway(Query) →QueryHandler →Db</p><p>EventStore ReadEvents Reader yaparken aldığımız hata</p><blockquote>com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.axonframework.serialization.UnknownSerializedType and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0])</blockquote><blockquote>Çözüm properties dosyamıza ekleyip serializer ayarlarını yapmamız gerekiyor</blockquote><blockquote>axon.serializer.general=jackson<br> axon.serializer.events=jackson<br> axon.serializer.messages=jackson</blockquote><p><a href="https://docs.axoniq.io/reference-guide/v/master/axon-framework/events/event-serialization">https://docs.axoniq.io/reference-guide/v/master/axon-framework/events/event-serialization</a></p><p><a href="https://docs.axoniq.io/reference-guide/axon-framework/events/event-processors#configuring-processors">Event Processors</a></p><p>CQRS Axon Örnek Kodlara github üzerinden erişip zenginleştirebilirsiniz.</p><p><a href="https://github.com/BilgehanYildiz/AxonCQRSSample">https://github.com/BilgehanYildiz/AxonCQRSSample</a></p><p>Not:Reader projesi aynı repositorynin içinde zipli olarak bulunmaktadır</p><p>Not:Örnek mantıksal bir işleyişten cok temel olarak axon birleşenlerinin denenmesi amacıyla oluşturulmuştur.</p><p>Not:Kaynakça olarak faydalanabilirsiniz</p><p><a href="https://blog.nebrass.fr/playing-with-cqrs-and-event-sourcing-in-spring-boot-and-axon/">https://blog.nebrass.fr/playing-with-cqrs-and-event-sourcing-in-spring-boot-and-axon/</a></p><p><a href="https://www.kindsonthegenius.com/microservices/cqrs-tutorial-with-axon-framework-step-by-step-project-for-beginners/">https://www.kindsonthegenius.com/microservices/cqrs-tutorial-with-axon-framework-step-by-step-project-for-beginners/</a></p><p><a href="https://progressivecoder.com/implementing-event-sourcing-using-axon-and-spring-boot-part-1/">https://progressivecoder.com/implementing-event-sourcing-using-axon-and-spring-boot-part-1/</a></p><p><a href="https://medium.com/@berkaybasoz/event-sourcing-and-cqrs-with-axon-and-spring-boot-part-1-6d1c1d4d054e">Event Sourcing and CQRS with Axon and Spring Boot — Part 1</a></p><p><a href="https://www.gencayyildiz.com/blog/microservice-mimarilerde-saga-pattern-ile-transaction-yonetimi/">https://www.gencayyildiz.com/blog/microservice-mimarilerde-saga-pattern-ile-transaction-yonetimi/</a></p><p><a href="https://sefikcankanber.medium.com/saga-pattern-nedir-e4a447bef361">https://sefikcankanber.medium.com/saga-pattern-nedir-e4a447bef361</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85fc5e15acd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SPRING WEB FLUX İLE REACTIVE REPOSITORYLER ÖRNEĞİ ve WEB FLUX la gelen KAVRAMLARA GENEL BAKIŞ]]></title>
            <link>https://medium.com/@bilgehan.yildiz/spring-web-flux-i%CC%87le-reactive-repositoryler-%C3%B6rne%C4%9Fi%CC%87-ve-web-flux-la-gelen-kavramlara-genel-baki%C5%9F-a44f7c0fd63b?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/a44f7c0fd63b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[webclient]]></category>
            <category><![CDATA[spring-web]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Sat, 02 Oct 2021 17:54:07 GMT</pubDate>
            <atom:updated>2021-10-02T17:54:07.351Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>SPRING WEB FLUX İLE REACTIVE REPOSITORYLER ÖRNEĞİ ve WEB FLUX la gelen KAVRAMLARA GENEL BAKIŞ</strong></p><p><strong>Bu yazımızda Spring WebFlux ve bu konu ile alakalı temel kavramların açıklamalarını yaptıktan sonra bir adet reactive repository örneği ve bunun webflux apiler ile kullanımına dair örnek yapıyor olacağız.</strong></p><p><strong>Reaktif Programlama Nedir?</strong></p><p>Reaktif programlama asenkron programlama mantığına dayanan gerçek zamanlı içerik güncellemeleri şeklinde tanımlamasını yapabiliriz.Object oriented programlama da gerçek hayattaki nesneler modellenerek bir design yapılırken reaktif programlama da gerçek hayattaki olaylar baz alınarak bir tasarım gerçekleşmektedir.Belli açılardan jms yapıları ile yaptığımız push mantığında çalışan event based tasarımları örnek olarak verebiliriz.</p><p><strong>Spring Web Flux Nedir?</strong></p><p>Spring Web Flux ise spring frameworkünün reaktif programlama için geliştirmiş olduğu bir frameworktür.Yapı olarak standart spring web frameworküne benzemekte (çoğu annotasyon ve kütüphane kullanımları ortaktır) olup özellikle non blocking işlemleri kolaylaştırmak için tasarlanmıştır.</p><p><strong>Standart Spring Web MVC deRestTemplate den WebClienta Geçiş</strong></p><p>Standart olarak resttemplate spring üzerinde http isteklerimizi yapmamızı sağlayan bir birleşen olarak karşımıza geliyordu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*2zMRtoqCgvyowv4BjetdXw.png" /></figure><p>Ancak spring 5 ile beraber,spring dokümantasyonlarına baktığımız zaman resttemplate artık maintenance mode alındığı ve yeni major bir feature gelmeyeceğini WebClient kullanımını düşünmemiz gerektiğini belirten bir ifade ile karşılaşıyoruz.</p><p>WebClient birleşeneni standart spring web kütüphanesi ile kullanmak mümkündür.</p><p>İşte burada spring reactive kütüphanesinin bir bileşeni olan WebClient reaktif,senkron ve asenkron çağrımlarda kullanabileceğimiz bir birleşen olarak karşımıza geliyor.</p><p>Burada da Spring 5 ile Gelen WebFlux yapısı ile artık reaktif programlamayı sadece jms level olarak değil api levelındada hayatımıza katabiliyoruz.</p><p>WebClient ile beraber temel olarak 2 method hayatımıza girmektedir.Exchange ve retrieve</p><p>Retrieve →Direkt olarak response bodye odaklanır ,kullanımı daha kolaydır</p><p>Exchage →Responsebody ek olarak http header ve status bilgilerinide alarak ,daha geniş ve detaylı bir exception handling ve kontrol mekanizması bizlere sunmaktadır.</p><p>WebClientla beraber gelen Mono ve Fetch yapıları ise</p><p>Mono →Tekil bir obje streami</p><p>Flux →Multiple bir obje streami üzerinden veri almak üzerine tasarlanmaktadır.</p><p>Ek olarak WebClientla beraber gelen concurency ve thread yönetim ve fireandforget mantıkları ilede detaylı bir asenkron çağrım yeteneklerini bizlere sunmaktadır.</p><p>WebClientla beraber detaylı bir exception handling ve retry fonksiyonaliteleri ise rest template yerine bazı noktalarda feign client kullanım ihtiyacını da ortadan kaldırmaktadır.Ek olarak feign clientın reaktif programlama da kullanılmak üzere gelen ek kütüphane ihtiyaçları yerine webclient direkt olarak reaktif çağrımları desteklemektedir.</p><p><strong>R2DBC Nedir?</strong></p><p>(Reactive Relational Database Connectivity) ,bu driver ile reactive repository ile çalışabiliyoruz.</p><p>Bunun için projemize dependency olarak r2dbc dependencysini ekliyoruz (spring data jpa yerine düşünebiliriz),not autoconfigure için starter kütüphaneside bulunmaktadır</p><blockquote>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.data&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-data-r2dbc&lt;/artifactId&gt;<br> &lt;version&gt;1.3.5&lt;/version&gt;<br> &lt;/dependency&gt;</blockquote><p>R2dbc üzerinde her veritabanının driver desteği olmamakla beraber oracle,sql server,h2,mongodb gibi sık kullanılan veritabanlarına ait driverlar mevcuttur</p><p>Spring Web de default olarak tomcat configure edilirken</p><p>Spring Web Fluxda default olarak Reactor Netty configure edilir.</p><p><strong>Netty</strong>:Asenkron Event Driven Network Application Framework.amaç daha az kaynak tüketimi ve daha az latency.</p><p><strong>Netty</strong>:NIO client server Framework</p><p><strong>NIO</strong>:Non Blocking Input Output</p><p><strong>BIO</strong>:Blocking Input Output</p><p>BIO modelinde javaya dönüş için datayı okurken veya yazarken işlemin sonlanmasını bekler.Bu süre zarfında ilgili thread bloke olur</p><p>NIO modelinde:İstek başlatıldıktan sonra tamamen bitmesi beklenmez.Yani bir kanala(channel) veri yazma isteğini başlatır ancak bu yazmanın tamamen bitmesini beklemez.Bu süre zarfında başka bir iş yürütebilir.</p><p><strong>Stream</strong>:Tek yönlü data transferi için kullanılır</p><p><strong>Channel</strong>:İki yönlü veri aktarım olanağı sağlar</p><p>BIO Stream Orienteddır</p><p>NIO:Buffer Orienteddır.Veriler kanal kullanarak daha fazla işlendiği bir ara belleğe okunur.</p><p>NIO ve BIO arasındaki farklar için aşağıdaki makale oldukça detaylı bilgi vermektedir.</p><p><a href="https://www.javatpoint.com/java-nio-vs-input-output">https://www.javatpoint.com/java-nio-vs-input-output</a></p><p><strong>Spring WebFlux ile Reactive Repository Örneği</strong></p><p>Projemizin pomunda olması gereken birleşenler</p><p>Not: r2dbc-h2 ve h2 birleşenleri sizin çalışanız database tipine göre değişmektedir.Biz örneği h2 ile yapacağımız için bu birleşenler gerekmektedir.</p><pre>&lt;dependencies&gt;</pre><pre>   &lt;dependency&gt;</pre><pre>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</pre><pre>      &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;</pre><pre>   &lt;/dependency&gt;</pre><pre>   &lt;dependency&gt;</pre><pre>      &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</pre><pre>      &lt;artifactId&gt;spring-boot-starter-data-r2dbc&lt;/artifactId&gt;</pre><pre>   &lt;/dependency&gt;</pre><pre>   &lt;dependency&gt;</pre><pre>      &lt;groupId&gt;io.r2dbc&lt;/groupId&gt;</pre><pre>      &lt;artifactId&gt;r2dbc-h2&lt;/artifactId&gt;</pre><pre>      &lt;scope&gt;runtime&lt;/scope&gt;</pre><pre>   &lt;/dependency&gt;</pre><pre>   &lt;dependency&gt;</pre><pre>      &lt;groupId&gt;com.h2database&lt;/groupId&gt;</pre><pre>      &lt;artifactId&gt;h2&lt;/artifactId&gt;</pre><pre>      &lt;version&gt;1.4.200&lt;/version&gt;</pre><pre>   &lt;/dependency&gt;</pre><p>Spring webflux ile default olarak netty server ayaklandırıldığı için h2 database default olarak spring console gelmemektedir.Bunun için ekstra olarak spring webflux üzerinde h2 console açmak için manuel olarak h2 server tetiklemek gerekmektedir.</p><p>Not:Buradan açılan console üzerinden h2 dbsi yaratamıyorsunuz file system üzerinde .mv.db uzantılı boş bir file yarattıktan sonra consoledan buraya giriş yapabilirsiniz.</p><blockquote>@Component<br> public class H2Server {<br> <br> <br> private Server webServer;<br> <br> @Value(“${h2-server.port}”)<br> Integer h2ConsolePort;<br> <br> @EventListener(ContextRefreshedEvent.class)<br> public void start() throws java.sql.SQLException {<br> <br> this.webServer = <em>createWebServer</em>(“-webPort”, h2ConsolePort.toString(), “-tcpAllowOthers”).start();<br> System.<em>out</em>.println(webServer.getURL());<br> }<br> <br> @EventListener(ContextClosedEvent.class)<br> public void stop() {<br> <br> this.webServer.stop();<br> }<br> <br> }</blockquote><p>WebFlux üzerinde kullanacağınız database ile r2dbc repositorylerini ilişkilendireceğiniz bir configuration sınıfına ihtiyanız olacak ve bunun tepesinde reactive repository bulmak için @EnableR2dbcRepositories olmalı ek olarak bu sınıf AbstractR2dbcConfiguration türemelidir</p><pre>@Configuration</pre><pre>@EnableR2dbcRepositories</pre><pre>public class DatabaseConfig extends AbstractR2dbcConfiguration {</pre><pre>    @Override</pre><pre>    @Bean</pre><pre>    public ConnectionFactory connectionFactory() {</pre><pre>        ConnectionFactoryOptions options =</pre><pre>                ConnectionFactoryOptions.<em>builder</em>()</pre><pre>                .option(<em>DRIVER</em>, &quot;h2&quot;)</pre><pre>                .option(<em>PROTOCOL</em>, &quot;file&quot;)  <em>// file, mem</em></pre><pre><em>                </em>.option(<em>HOST</em>, &quot;localhost&quot;)</pre><pre>                .option(<em>USER</em>, &quot;sa&quot;)</pre><pre>                .option(<em>PASSWORD</em>, &quot;123&quot;)</pre><pre>                .option(<em>DATABASE</em>, &quot; C:\\h2\\h2&quot;).build();</pre><pre>        <em>//ConnectionFactory connectionFactory = ConnectionFactories.get(&quot;r2dbc:h2:file://C:/h2/h2&quot;);</em></pre><pre><em>        </em>ConnectionFactory connectionFactory=ConnectionFactories.<em>get</em>(options);</pre><pre>        return connectionFactory;</pre><pre>    }</pre><pre>    @Bean</pre><pre>    ReactiveTransactionManager transactionManager(ConnectionFactory connectionFactory) {</pre><pre>        return new R2dbcTransactionManager(connectionFactory);</pre><pre>    }</pre><pre>}</pre><p>Repositoryde kullanmak üzere nesnemizi hazırlıyoruz.Burada dikkat edilmesi gereken nokta ise @Id ve @Column gibi annatasyonların springframework.data paketi altından gelmesi gerektiği.javax altından gelen annotasyonlar sadece relational jpalar için kullanılabileceğinden springden gelenleri tercih ediyoruz</p><pre>import org.springframework.data.annotation.Id;</pre><pre>import org.springframework.data.annotation.Transient;</pre><pre>import org.springframework.data.domain.Persistable;</pre><pre>import org.springframework.data.relational.core.mapping.Column;</pre><p>Standart jpa nesnelerinden Diğer bir nokta ise ReactiveRepositorylerde Save Methodunu kullanabilmek için Persistable implemene edilip isnew fonksiyonunun override edilmesi gerekliliğidir</p><p>Not:Persistable ayarı yapılmadığı takdirde save methodunda aşağıdaki hata oluşmaktadır</p><pre>org.springframework.dao.TransientDataAccessResourceException: Failed to update table [Test]. Row with Id [4] does not exist.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*zjoq_GB9GITqjbSRz0KhNw.png" /></figure><p>Repository sınıfımız ise ReactiveCrudRepository tipinden türemelidir.</p><pre>public interface TestRepository extends ReactiveCrudRepository&lt;TestEntity,Integer&gt;</pre><pre>{</pre><pre>}</pre><pre>Servis sınıfımızdaki methodlardan da anlaşılacağı üzere Mono tek bir obje,Flux ise Obje Listesi şeklinde itemları taşımak içindir.</pre><p>Save methodu ise subscribe (async) veya block(thread wait) şeklinde çağrım yapılmadığı takdirde çalışmaya başlayamayacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*gJAE9xlN31YMujxHEDYlkQ.png" /></figure><p>Controller sınıfımızda ise service kısmında yazdığımız methodları call ederek çağırım yapabiliyoruz.</p><pre>@Autowired<br><br>MyReactiveService myReactiveService;</pre><pre>@GetMapping(&quot;alldbsample&quot;)<br><br>public Flux&lt;TestEntity&gt; getAllFromDBSample(){<br><br>    return myReactiveService.getAllEntity();<br><br>}<br><br><br><br>@GetMapping(&quot;alldb2&quot;)<br><br>public Mono&lt;TestEntity&gt; getAllFromDB2()<br><br>{<br><br>    return myReactiveService.getAllEntityMono();<br><br>}<br><br><br><br>@GetMapping(&quot;save&quot;)<br><br>public Mono&lt;String&gt; BulkSave()<br><br>{<br><br>    for (int i=5;i&lt;10000;i++)<br><br>    {<br><br>        TestEntity t=new TestEntity();<br><br>        t.setId(i);<br><br>        t.setName(&quot;Bilgehan&quot;+i);<br><br>        t.setInfo(&quot;x&quot;+i);<br><br>        myReactiveService.save(t);<br><br><br><br>    }<br><br>    return Mono.<em>just</em>(&quot;Bitti&quot;);<br><br>}</pre><pre>//Flux objelerinde doOnNext ile gelen her elemanı içerisinde işlem yapabiliriz.</pre><pre>@GetMapping(&quot;alldb&quot;)<br><br>public Flux&lt;TestEntity&gt; getAllFromDB() throws Exception<br><br>{<br><br>    Flux&lt;TestEntity&gt; fluxlist= myReactiveService.getAllEntity();<br><br><br><br>    fluxlist.delayElements(Duration.<em>ofMillis</em>(1000)).doOnNext(u -&gt; System.<em>out</em>.println(&quot;listUsers1 received &quot; + u.getName())).<br><br>            subscribe();<br><br>    return fluxlist;<br><br>}</pre><p>//Bu örnekteki gibi dönen objelerde defualtIfEntity veya map komutları ile farklı değer atamaları yapabiliyoruz</p><pre>@GetMapping(&quot;{id}&quot;)<br><br>public Mono&lt;ResponseEntity&lt;TestEntity&gt;&gt; getTestEntityId(@PathVariable int id){<br><br>    return this.myReactiveService.findByIDMono(id)<br><br>            .map(ResponseEntity::<em>ok</em>)<br><br>            .defaultIfEmpty(ResponseEntity.<em>notFound</em>().build());<br><br>}</pre><p>Kodların tamamına aşağıdaki github adresinden ulaşabilirsiniz</p><p>https://github.com/BilgehanYildiz/SpringWebFluxReactiveRepo</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a44f7c0fd63b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SPRING BOOT İLE MICROSERVICE REGISTRY VE DISCOVERY PATTERNLERİNE BAKIŞ]]></title>
            <link>https://medium.com/@bilgehan.yildiz/spring-boot-i%CC%87le-microservice-registry-ve-discovery-patternleri%CC%87ne-baki%C5%9F-a25fb5dd340c?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/a25fb5dd340c</guid>
            <category><![CDATA[eureka]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[patterns]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Thu, 23 Sep 2021 18:40:16 GMT</pubDate>
            <atom:updated>2021-09-23T18:40:16.067Z</atom:updated>
            <content:encoded><![CDATA[<p>Microservisler kullanımı ile alakalı olarak artılarına baktığımız zaman en büyük artılarından biri kolayca yük altında arttırılıp azaltılabilen yapılar olması olarak görürürüz.Tabi bu dinamiklik beraberinde altyapısal olarak daha karmaşık olan yapılara yol açmaktadır.Bu yazımızda bu altyapısal karmaşıklıklarda microservislerin birbirlerin yerlerini bulmaları için yöntemleri ele alıyor olacağız.</p><p>Genel kavramlara baktıktan sonra bunların spring boot üzerinde örneklerinin nasıl olacağını bakıyor olacağız.</p><p><strong>SERVICE Discovery Nedir?</strong></p><p>Bir micro servis diğer microservise erişim sağlayabilmek için onun network üzerindekini yerini bilmek zorundadır.</p><p>Service Discovery temel olarak 3 kavram üzerinde durur</p><p>1-)Discover:Microservislerin http levelda haberleşebilmeleri için birbirlerinin ip ve port bilgilerini bulma yöntemleridir.</p><p>İki tip Discovery Pattern vardır</p><p>· Server Side Discovery:Burada client ile hizmet alacağı microservisler arasında bir load balancer mevcuttur.Client isteği loadbalancera yapar.Hizmet verecek microservisler ise loadbalancerın registrysine kayıt olur.Daha sonra loadbalancer ilgili isteği hizmet sağlayan microservise gönderir.Clientside discovery göre avantajı hizmet almak isteyen ve vermek isteyen microservisler arası direkt bir bağlantı olmayıp iki tarafta sadece loadbalancerı bilmektedir.</p><p>· Client Side Discovery:burada client hizmet alacağı servisin yerini bulmak ve atacağı istek için nasıl bir loadbalance yöntemi kullanacağından sorumludur.Öncelikli olarak service registry gidip hangi instanceların ayakta olduğu bilgisini elde eder.Daha sonra ise hizmet almak istediği instance isteği gönderir.</p><p>Şekiller ve daha fazla açıklama için</p><p><a href="https://www.nginx.com/blog/service-discovery-in-a-microservices-architecture/">https://www.nginx.com/blog/service-discovery-in-a-microservices-architecture/</a></p><p>2-)Load Balancing:Bir istek geldiği zaman gelen istediğin ne şekilde dağıtılacağını belirler.Cluster yapılarda eğer arka planda down olan instancelar varsa bunların yük almasını engeller</p><p>3-)Health Check Servisi:Hizmet sağlayan bir microservisin ayakta olup olmadığı bilgisini registry ile paylaşabilmesine sağlayan yöntemdir.Bu sayede registry eğer health check bilgisi alamaz ise buraya istek göndermeyi engelleyebilir.</p><p><strong>SERVICE REGISTRY Nedir?</strong></p><p>Bir servis bir diğer microservisin yerini tespit edebilmek için client side discovery veya serverside discovery yöntemlerinden birini kullanmaktadır.Dolayısıyla microservislerin yerini tutup gelen isteklerinin nereye gideceğini belirleyecek yapılara ihtiyaçlar vardır.</p><p>Burada örnek olarak Netflixin Eureka serverı bu yapıyı bize client side discovery için sağlayan toollardan biridir.</p><p>Öteki tarafta nginx ise server side load balancer olarak kullanabileceği için server side discovery amacıyla kullanılabilir.</p><p>Spring boot ile ClientSide Discovery Örneğimiz için 3 adet microservis oluşturacağız</p><p>1-)Service Registry EurekaServer</p><p>2-)Provider MicroService</p><p>3-)Consumer Microservice</p><p><strong>1-)Service Registry EurekaServer</strong></p><p>ilk etapta service registrymizi ayaklandıralım eureka server</p><p>&lt;dependencies&gt;<br> &lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-server&lt;/artifactId&gt;</p><p>&lt;version&gt;3.0.4&lt;/version&gt;<br> &lt;/dependency&gt;</p><p>Ve bazı versiyonlar için java 11 ile kullanıldığında jaxb-runtime eklemek gerekebilir</p><pre>&lt;groupId&gt;org.glassfish.jaxb&lt;/groupId&gt;</pre><pre>&lt;artifactId&gt;jaxb-runtime&lt;/artifactId&gt;</pre><pre>&lt;/dependency&gt;</pre><p>Daha sonra spring starter classımızın tepesine @EnableEurekaServer annatosyanonu koyuyoruz</p><pre>@EnableEurekaServer</pre><pre>@SpringBootApplication</pre><pre>public class EurekaserverApplication {</pre><pre>   public static void main(String[] args) {</pre><pre>      SpringApplication.<em>run</em>(EurekaserverApplication.class, args);</pre><pre>   }</pre><pre>}</pre><p>En son application.properties dosyamıza aşağıdaki ayarları ekleyip</p><pre>server.port=8091</pre><pre>eureka.client.register-with-eureka=false</pre><pre>eureka.client.fetch-registry=false</pre><pre>eureka.instance.hostname=myserviceregistry</pre><p>projemizi çalıştırarak service registry mizi ayağa kaldıyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/675/1*r9uePaqL_xQGkaGty_ejcw.png" /></figure><p><strong>2-)Provider MicroService</strong></p><p>Spring initializerda 2 adet dependency seçiyoruz eurekaclient ve healthcheck için spring actuator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*JiiHI7kIzLRavLw8WKkNWw.png" /></figure><p>Pom dosyamız</p><pre>&lt;dependency&gt;</pre><pre>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;</pre><pre>   &lt;artifactId&gt;spring-boot-starter-actuator&lt;/artifactId&gt;</pre><pre>&lt;/dependency&gt;</pre><pre>&lt;dependency&gt;</pre><pre>   &lt;groupId&gt;org.springframework.cloud&lt;/groupId&gt;</pre><pre>   &lt;artifactId&gt;spring-cloud-starter-netflix-eureka-client&lt;/artifactId&gt;</pre><pre>&lt;/dependency&gt;</pre><p>//Eurekada gözükecek uygulama adı</p><pre>spring.application.name=providerservice</pre><pre>//Eureka dan ara ve register ol ayarları</pre><pre>eureka.client.register-with-eureka=true</pre><pre>eureka.client.fetch-registry=true</pre><pre>eureka.client.enabled=true</pre><pre>//Eureka server url sonunda eureka eklenmeli</pre><pre>eureka.client.serviceUrl.defaultZone=http://localhost:8091/eureka</pre><p>Bu ayarlardan sonra start ettiğimizde artık eureka serverda servisimizin register olduğunu görebiliyoruz.</p><p><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html"><strong>https://docs.spring.io/spring-boot/docs/current/reference/html/actuator.html</strong></a></p><p><strong>Actuator ayarlarının detaylarına yukarıdaki linkten bakılabilir</strong></p><p><a href="http://localhost:8080/actuator/health">http://localhost:8080/actuator/health</a></p><p>Actuator servisini aktiflemek için application.propertiese aşağıdaki parametreleri ekliyoruz</p><pre>management.endpoints.web.exposure.include=*</pre><pre>management.endpoints.health.show-details=always</pre><pre>management.endpoints.jmx.exposure.include=*</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/419/1*AWrdSXdoDnX8X3kh6uJfJA.png" /></figure><p>3-)Consumer Microservice :burada dependecy olarak yine actuator ve eureka client kütüphaneleri ekliyoruz projemize</p><p>Eğer bu uygulamamızda eureka ya register olacaksa verilecek applicationnamein providerdan farklı olması gerektiğine dikkat etmek lazım.</p><pre>server.port=8081</pre><pre>spring.application.name=consumerservice</pre><pre>eureka.client.register-with-eureka=true</pre><pre>eureka.client.fetch-registry=true</pre><pre>eureka.client.enabled=true</pre><pre>eureka.client.serviceUrl.defaultZone=http://localhost:8091/eureka</pre><pre>management.endpoints.web.exposure.include=*</pre><pre>management.endpoints.health.show-details=always</pre><pre>management.endpoints.jmx.exposure.include=*</pre><p>Consumer servisimizde yapmamız gereken ek iş olarak</p><p>DiscoveryClient paketi ile serviceregistryimiz olan eurekaya giderek gideceğimiz microservisin networkteki yerini öğrenmek gerekiyor.Daha sonra ise direkt olarak çağrım yapabiliyoruz(Client side discovery senaryosu).İstenirse burda yine netflix ribbon kütüphanesi yardımıyla client üstünde load balancing yapılabilir ancak bizim örneğimiz tek bir servis olduğu için kullanmadık.</p><pre>package com.demo.consumerservice;</pre><pre>import org.springframework.cloud.client.ServiceInstance;</pre><pre>import org.springframework.cloud.client.discovery.DiscoveryClient;</pre><pre>import org.springframework.beans.factory.annotation.Autowired;</pre><pre>import org.springframework.http.HttpStatus;</pre><pre>import org.springframework.http.ResponseEntity;</pre><pre>import org.springframework.web.bind.annotation.GetMapping;</pre><pre>import org.springframework.web.bind.annotation.RequestMapping;</pre><pre>import org.springframework.web.bind.annotation.RestController;</pre><pre>import org.springframework.web.reactive.function.client.WebClient;</pre><pre>import java.util.List;</pre><pre>@RestController</pre><pre>@RequestMapping(&quot;api/consumer&quot;)</pre><pre>public class ExampleController {</pre><pre>    @Autowired</pre><pre>    private DiscoveryClient discoveryClient;</pre><pre>    @GetMapping(&quot;callservice&quot;)</pre><pre>    public ResponseEntity helloworld()</pre><pre>    {</pre><pre>        List&lt;ServiceInstance&gt; instanceList=this.discoveryClient.getInstances(&quot;PROVIDERSERVICE&quot;);</pre><pre>        String BaseUri=instanceList.get(0).getUri().toString();</pre><pre>        String path=&quot;/api/example/hello&quot;;</pre><pre>        WebClient client = WebClient.<em>create</em>(BaseUri+path);</pre><pre>        WebClient.ResponseSpec responseSpec  = client.get().retrieve();</pre><pre>        String responseBody = responseSpec.bodyToMono(String.class).block();</pre><pre>        return ResponseEntity.<em>status</em>(HttpStatus.<em>OK</em>).body(&quot;Çağırıldı&quot;+responseBody);</pre><pre>    }</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*tDJNy0Wvsgx_3ZFjfv6VHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*Y0zPFXAkbhpHUV0dRdgdIQ.png" /></figure><p>Çağrımızı yapıp cevabımızı almış oluyoruz</p><p>Kod örneklerine aşağıdaki urlden erişebilirsiniz.</p><p><a href="https://github.com/BilgehanYildiz/SpringServiceRegistryDiscovery">https://github.com/BilgehanYildiz/SpringServiceRegistryDiscovery</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a25fb5dd340c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SPRING BOOT 5 WEBCLIENT İNCELEMESİ]]></title>
            <link>https://medium.com/@bilgehan.yildiz/spring-boot-5-webclient-i%CC%87ncelemesi%CC%87-3a21cdf0d732?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a21cdf0d732</guid>
            <category><![CDATA[spring-webflux]]></category>
            <category><![CDATA[webclient]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Sat, 11 Sep 2021 18:08:10 GMT</pubDate>
            <atom:updated>2021-09-11T18:08:10.359Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Bu yazımız da spring webflux kütüphanesi ile gelen WebClient componentini standart bir spring web (nonreactive) uygulamasında kullanımını ele alıyor olacağız.</strong></p><p>Spring 5.0 dan itibaren AsyncRestTemplate deprecated olmuş durumdadır.Ek olarak RestTemplate özelliğine baktığımızda ise Spring 5.0 dan itibaren RestTemplate deprecate edilmese de artık minör change ve bug fixler dışında bir desteğinin olmayacağı spring tarafından ilan edilmiş durumdadır.</p><p>Tüm bunlara karşılık Spring de önerilen yöntem reactive çağrımlara da destek verilen WebClient metodlarını kullanmak olacaktır.</p><p>Resttemplate thread blocking olarak yani senkron olarak çalışırken,WebClient senkron kullanabileceği gibi asenkron veya streaming senaryolarında da kullanılabilmektedir.</p><p>Bunun yanında WebClient ile feignclienttakine benzer retry özelliklerini de taşımaktadır.</p><p>Asenkron özelliklerine karşın WebClient threadsafe dir,yani immutabledır.</p><p>WebClient Spring WebFlux Frameworkünün bir parçası olarak gelmektedir.WebFlux dependency ekleyerek hızlıca spring projenizde kullanabilirsiniz.</p><blockquote>&lt;<strong>dependency</strong>&gt;</blockquote><blockquote>&lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;</blockquote><blockquote>&lt;<strong>artifactId</strong>&gt;spring-boot-starter-webflux&lt;/<strong>artifactId</strong>&gt;</blockquote><blockquote>&lt;/<strong>dependency</strong>&gt;</blockquote><p>Spring webflux birleşenlerini springweb mvc ilede kullanmak mümkündür.</p><p><a href="https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html">https://docs.spring.io/spring-framework/docs/current/reference/html/web-reactive.html</a></p><pre>Uygulama  da  aynı anda spring-boot-starter-webflux ve spring-boot-starter-web varsa default olarak spring-boot-starter-web ile spring mvcye göre uygulamamız yapılanır.</pre><p><a href="https://spring.io/guides/gs/reactive-rest-service/">Getting Started | Building a Reactive RESTful Web Service</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*8_dV6GzJACsT1l51G7w4ag.png" /></figure><p>Spring web flux reaktif web uygulamaları oluşturmak için ortaya çıkmış bir yapıdır.Reaktif programlama bir olay olduğunda buna göre tepki verme mantığına dayalı olay bazlı programlama şeklidir.Kısaca pub sub (Publisher-subscriber yöntemli apiler yazmamıza olanak sağlar.)</p><p>İki adet Publisher tipi vardır.</p><p>Mono:Tek bir değer döndürmeye sağlar (Single object veya optional)</p><p>Flux:Çoklu değer döndürmeyi sağlar</p><p><strong>Örnek Senaryo 1</strong> WebClient ile Senkron ve Asenkron Get Çağrımı</p><p>Async çağrımda subscribe denilene kadar thread aktif hale gelmez</p><pre>@RestController<br> @RequestMapping(“api/sample1”)<br> public class Sample1Controller {<br> <br> <br> @GetMapping(path = “author/sync”)<br> public ResponseEntity getAuthor() throws Exception<br> {<br> WebClient client = WebClient.<em>create</em>(“http://localhost:8092/api/author&quot;);<br> WebClient.ResponseSpec responseSpec = client.get().retrieve();<br> Email responseBody = responseSpec.bodyToMono(Email.class).block();<br> return ResponseEntity.<em>ok</em>(“Bilgiler alındı”);<br> }<br> <br> <br> @GetMapping(path = “author/async”)<br> public ResponseEntity getAuthorAsync() throws Exception<br> {<br> WebClient client = WebClient.<em>create</em>(“http://localhost:8092/api/author”);<br> WebClient.ResponseSpec responseSpec = client.get().retrieve();<br> <em><br> </em>Mono&lt;Email&gt; emailMono=responseSpec.bodyToMono(Email.class);<br> emailMono.subscribe(result-&gt;{System.<em>out</em>.println(result.getName() + OffsetDateTime.<em>now</em>());});<br> Thread.<em>sleep</em>(20000);<br> System.<em>out</em>.println(“Çıkmadan önceki son adım”+ OffsetDateTime.<em>now</em>());<br> return ResponseEntity.<em>ok</em>(“Bilgiler alındı”);<br> }<br> <br> <br> }</pre><pre>Çağırılan taraftaki provider microservisimize ait method</pre><pre>@GetMapping(path = “api/author” )<br> public ResponseEntity getAuthor()<br> {<br> <br> Email email=new Email();<br> email.setName(“Bilgehan YILDIZ”);<br> email.setSenderEmail(“bilgehanyildiz@bilgehanyildiz.com”);<br> <em><br> </em>return ResponseEntity.<em>ok</em>(email);<br> }</pre><p><strong>Örnek Senaryo 2</strong> Senkron Post Çağrımı Single ve List şeklinde dönüşler için</p><p>createCustomerBulk metodunda dikkat edilmesi gereken iki husus vardır.</p><p>1-)Mono bir objenin içine liste atıyoruz.Burda provider olan apimiz standart bir rest servisi,reaktif bir servis değil dolayısıyla Listte bir obje olduğu için bu şekilde kullanım yapabiliyoruz Mono ve Flux özellikle stream mantığında işlerde farklılık göstermektedir.</p><p>2-)Liste olduğu için geri dönüş tipini ParameterizedTypeReference sayesinde alabiliyorum.WebClientta gelen obje liste ise bu şekilde casting yapabiliriz.</p><pre>@RestController<br> @RequestMapping(“api/sample2”)<br> public class Sample2Controller {<br> <br> @PostMapping(path = “api/customer”,consumes = MediaType.<em>APPLICATION_JSON_VALUE</em>)<br> public ResponseEntity createCustomer(@RequestBody Customer request) throws Exception<br> {<br> <em>//TODO Customer Creation process<br> //<br> <br> </em>Email email=new Email();<br> email.setName(request.getName());<br> email.setEmail(request.getEmail());<br> <br> WebClient client = WebClient.<em>create</em>(“http://localhost:8092”);<br> MyResponse sendEmail = client.post()<br> .uri(“/api/sendemail”)<br> .header(HttpHeaders.<em>CONTENT_TYPE</em>, MediaType.<em>APPLICATION_JSON_VALUE</em>)<br> .body(Mono.<em>just</em>(email), Email.class)<br> .retrieve()<br> .bodyToMono(MyResponse.class).block();<br> <br> <br> return ResponseEntity.<em>ok</em>(“Musteri yaratildi”);<br> }<br> <br> @PostMapping(path = “api/customerbulk”,consumes = MediaType.<em>APPLICATION_JSON_VALUE</em>)<br> public ResponseEntity createCustomerBulk(@RequestBody Customer request) throws Exception<br> {<br> <em>//TODO Customer Creation process<br> //<br> <br> </em>Email email=new Email();<br> email.setName(request.getName());<br> email.setEmail(request.getEmail());<br> <br> WebClient client = WebClient.<em>create</em>(“http://localhost:8092”);<br> List&lt;Email&gt; sendEmail = client.post()<br> .uri(“/api/sendbulk”)<br> .header(HttpHeaders.<em>CONTENT_TYPE</em>, MediaType.<em>APPLICATION_JSON_VALUE</em>)<br> .body(Mono.<em>just</em>(email), Email.class)<br> .retrieve()<br> .bodyToMono(new ParameterizedTypeReference&lt;List&lt;Email&gt;&gt;() {}).block();<br> <br> return ResponseEntity.<em>ok</em>(“Musteri yaratildi”);<br> }<br> <br> }</pre><pre>Çağırılan taraftaki provider microservisimize ait methodlar</pre><pre>@PostMapping(path = “api/sendemail”,consumes = MediaType.<em>APPLICATION_JSON_VALUE </em>)<br> public ResponseEntity createCustomer(@RequestBody Email request)<br> {<br> <br> <em>//TODO Mail Sending process<br> //<br> </em>MyResponse response=new MyResponse();<br> response.setResult(“Email gonderildi”);<br> return ResponseEntity.<em>ok</em>(response);<br> }<br> <br> @PostMapping(path = “api/sendbulk”,consumes = MediaType.<em>APPLICATION_JSON_VALUE </em>)<br> public ResponseEntity&lt;List&lt;Email&gt;&gt; senbBulkMail(@RequestBody Email request)<br> {<br> <br> <em>//TODO Mail Sending Bulk process<br> //<br> </em>List&lt;Email&gt; emails=new ArrayList&lt;&gt;();<br> Email email1=new Email();<br> email1.setEmail(“b@b.com”);<br> email1.setName(“b”);<br> email1.setSenderEmail(request.getEmail());<br> Email email2=new Email();<br> email2.setEmail(“c@c.com”);<br> email2.setName(“c”);<br> email2.setSenderEmail(request.getEmail());<br> emails.add(email1);<br> emails.add(email2);<br> <br> return ResponseEntity.<em>ok</em>(emails);<br> }</pre><p><strong>Örnek Senaryo 3 ExchangeToMono kullanımı</strong></p><p>WebClient için Retrieve vs Exchange</p><p>Retrieve sadece reponse nasıl extract edeceğimizi belirler.4XX ve 5XX Statü kodlarında WebClientResponseException fırlatır. onstatus özelliği ile error handling yapabiliriz</p><p>Exchange fonksiyonları,retrieve göre ClientResponse üzerinde daha fazla kontrol sağlar örneğin httpstatülerine göre farklı işlemler dönüşler yapmak gibi daha advance senaryolar için uygundur</p><pre>@RestController<br> @RequestMapping(“api/sample3”)<br> public class Sample3Controller {<br> <br> @GetMapping(path = “author/exhange”)<br> public ResponseEntity getAuthor() throws Exception,Throwable<br> {<br> WebClient client = WebClient.<em>create</em>(“http://localhost:8092/api/author&quot;);<br> <br> <br> <br> Mono&lt;Object&gt; monoresponse = client.get().exchangeToMono(<br> response-&gt;{<br> if (response.statusCode().equals(HttpStatus.<em>OK</em>))<br> {<br> return response.bodyToMono(Email.class);<br> } else if (response.statusCode().is4xxClientError()) {<br> return Mono.<em>error</em>(new IllegalArgumentException(“format hatası”));<br> }<br> else<br> {<br> return Mono.<em>error</em>(new Exception(“beklenmeyen hata”));<br> <em>//Just En primitive mono dönüş şeklidir.Tek bir instance üretir<br> //Defer her subscribe için farklı değer üretir.<br> </em>}<br> });<br> <br> Email email= (Email) monoresponse.block();<br> return ResponseEntity.<em>ok</em>(“Bilgiler alındı”);<br> }<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*3dKHRoQRgW5BDaPESDThLA.png" /></figure><p><strong>Örnek Senaryo 4</strong>:WebClient toEntity ve Timeout örnekleri</p><p>toEntity ile ResponseEntity şeklinde veri retrieve etmek</p><pre>@GetMapping(path = “entity”)<br> public ResponseEntity getEntity()<br> {<br> WebClient client = WebClient.<em>create</em>(“http://localhost:8092/api/author&quot;);<br> ResponseEntity&lt;Email&gt; statusEntity = client.get().retrieve().toEntity(Email.class).block();<br> return ResponseEntity.<em>ok</em>(“Bilgiler alındı”);<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*3dKHRoQRgW5BDaPESDThLA.png" /></figure><p>Mono.Just ve Mono.Defer mono.just sadece bir tane immutable object create eder ve değer değişse bile sonucu değişmez Mono.defer değere göre değişim gösterir</p><pre>WebClienta timeout vermek için reactor.netty.http.client.HttpClient</pre><p>Paketindeki HttpClient sınıfından faydalanıyoruz</p><p>Aşağıdaki örnekte 4 sn içinde cevap alamazsak apiden timeout hatası alınacaktır.</p><pre>@GetMapping(path = “timeout”)<br> public ResponseEntity getTimeout()<br> {<br> <br> HttpClient httpClient = HttpClient.<em>create</em>()<br> .responseTimeout(Duration.<em>ofSeconds</em>(4));<br> WebClient client = WebClient.<em>builder</em>()<br> .clientConnector(new ReactorClientHttpConnector(httpClient))<br> .baseUrl(“http://localhost:8092/api/author”).build();<br> <br> ResponseEntity&lt;Email&gt; statusEntity = client.get().retrieve().toEntity(Email.class).block();<br> return ResponseEntity.<em>ok</em>(“Bilgiler alındı”);<br> }</pre><p>Senaryo 5 Retry özellikleri</p><p>WebClient ile Düz olarak kaç kere retry edeceğià retry(3).</p><pre>Belli bekleme aralıklarına göre retry etmesià retryWhen(Retry.<em>fixedDelay</em>(2, Duration.<em>ofSeconds</em>(5)))</pre><p>Belli koşullara göre retry etme senaryosu gibi durumları kolayca yazabiliriz.</p><pre>@GetMapping(path = “timeout”)<br> public ResponseEntity getTimeout()<br> {<br> <br> HttpClient httpClient = HttpClient.<em>create</em>()<br> .responseTimeout(Duration.<em>ofSeconds</em>(4));<br> WebClient client = WebClient.<em>builder</em>()<br> .clientConnector(new ReactorClientHttpConnector(httpClient))<br> .baseUrl(“http://localhost:8092/api/author”).build();</pre><pre>//Düz olarak 3 kere deneme yap<br> Email email = client.get().retrieve().bodyToMono(Email.class).retry(3).block();<br> return ResponseEntity.<em>ok</em>(“Bilgiler alındı”);</pre><pre>5 saniye aralıklı 2 deneme yap</pre><pre>Email email2 = client.get().retrieve().bodyToMono(Email.class).retryWhen(Retry.<em>fixedDelay</em>(2, Duration.<em>ofSeconds</em>(5))).block();</pre><pre>}<br> <br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*S1yKow-Tkm3JUjrt8FnzRg.png" /></figure><pre>Spesifik hata geldiğinde retry yap</pre><pre>@GetMapping(path = “retryforspecificerror”)<br> public ResponseEntity retryForSpecific()<br> {<br> <br> HttpClient httpClient = HttpClient.<em>create</em>()<br> .responseTimeout(Duration.<em>ofSeconds</em>(4));<br> WebClient client = WebClient.<em>builder</em>()<br> .clientConnector(new ReactorClientHttpConnector(httpClient))<br> .baseUrl(“http://localhost:8092/api/author”).build();<br> <br> Email email = client.get().retrieve()<br> <br> <em>/*.onStatus(HttpStatus::is5xxServerError,<br> response -&gt; Mono.error(new Exception(“Server error unexpected”)))*/<br> </em>.bodyToMono(Email.class).<br> retryWhen(Retry.<em>fixedDelay</em>(3, Duration.<em>ofSeconds</em>(1)).<br> filter(throwable -&gt; throwable instanceof WebClientRequestException)).block();<br> return ResponseEntity.<em>ok</em>(“Bilgiler alındı”);</pre><pre>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*pwpqK7MRxO4PiIeWOmwJRQ.png" /></figure><p>Kodlara aşağıdaki repodan ulaşabilirsiniz.</p><p><a href="https://github.com/BilgehanYildiz/SpringWebClientSample"><strong>https://github.com/BilgehanYildiz/SpringWebClientSample</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a21cdf0d732" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SPRING BOOT ile Microservis Communication Patternlerinin Örnekleri]]></title>
            <link>https://medium.com/@bilgehan.yildiz/spring-boot-ile-microservis-communication-patternlerinin-%C3%B6rnekleri-af2d82b51d30?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/af2d82b51d30</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Sat, 04 Sep 2021 18:45:53 GMT</pubDate>
            <atom:updated>2021-09-04T18:45:53.542Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Senkron İletişim(Syncronous Communication) Patterni</strong></h3><p>Response Request Yaklaşımı olarak da bilinir.Rest,grpc ve grapql en temel yaklaşımlardan bazılarıdır.</p><p>Rest ve Grapql text bazlı,grpc ise binary data formatları kullanılır.</p><p>İlk örneğimiz olarak ikitane microservis projesi oluşturalım.</p><p>Senkron iletişim örneği olarak bu örnekte spring frameworkte yaygın kullanılan <strong>resttemplate</strong> yerine spring dökümanlarında önerilen <strong>webclient</strong> yapısı ile gidilecektir.Detaylarına spring dokümanlarından bakabilirsiniz.</p><p><a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/index.html?org/springframework/web/client/RestTemplate.html">https://docs.spring.io/spring-framework/docs/current/javadoc-api/index.html?org/springframework/web/client/RestTemplate.html</a></p><p><strong>NOTE:</strong> As of 5.0 this class is in maintenance mode, with only minor requests for changes and bugs to be accepted going forward. Please, consider using the org.springframework.web.reactive.client.WebClient which has a more modern API and supports sync, async, and streaming scenarios.</p><p>Öncelikle iki farklı microservis projesi create edelim.</p><p>Birinci microservisimize bir adet müşteri create apisi yazarak diğer microservisimizi çağıralım.</p><p>Bu microservisimiz rest call yapacağı için pomuna webclient kullanabilmesi için spring webflux dependecysini eklememiz gerekmektedir.</p><blockquote>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-webflux&lt;/artifactId&gt;<br> &lt;/dependency&gt;</blockquote><pre>@RestController<br> public class CustomerController {<br> <br> @PostMapping(path = “api/customer”,consumes = MediaType.<em>APPLICATION_JSON_VALUE</em>)<br> public ResponseEntity createCustomer(@RequestBody Customer request)<br> {<br> <br> <em>//TODO Customer Creation process<br> //<br> <br> </em>WebClient client = WebClient.<em>create</em>(“http://localhost:8092”);<br> Email email=new Email();<br> email.setName(request.getName());<br> email.setEmail(request.getEmail());<br> <br> MyResponse sendEmail = client.post()<br> .uri(“/api/sendemail”)<br> .header(HttpHeaders.<em>CONTENT_TYPE</em>, MediaType.<em>APPLICATION_JSON_VALUE</em>)<br> .body(Mono.<em>just</em>(email), Email.class)<br> .retrieve()<br> .bodyToMono(MyResponse.class).block();<br> <br> <br> return ResponseEntity.<em>ok</em>(“Musteri yaratildi”);<br> }<br> }</pre><p>Not:Monoyu bir completablefuture gibi düşünebiliriz.Datayı çekerken ya Mono&lt;T&gt; seklinde kullanmamız veya direkt olarak bizim istediğimiz result body serialize olmasını istiyorsak sonuna block koyarak kullanmamız gerekmektedir.</p><p>Not:Kullanılan tiplerin detayları Resim Model 1 de gösterilmiştir</p><p>Resim Model 1</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*kqHj2WrrSzTk4nzEBMHT6Q.png" /></figure><p>Microservis2 miz ise email gönderimi yapan bir microservis olsun.</p><pre>@RestController<br> public class EmailController {<br> <br> @PostMapping(path = “api/sendemail”,consumes = MediaType.<em>APPLICATION_JSON_VALUE </em>)<br> public ResponseEntity createCustomer(@RequestBody Email request)<br> {<br> <br> <em>//TODO Mail Sending process<br> //<br> </em>MyResponse response=new MyResponse();<br> response.setResult(“Email gonderildi”);<br> return ResponseEntity.<em>ok</em>(response);<br> }<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*5P7wsEavzqpVbTExj22gPQ.png" /></figure><p>Servislerimizi çalıştırdığımız zaman müşteri yaratma apimiz gidip email apisini senkron olarak çağırıp sonucu alabilmiş durumdadır.</p><p>Peki ya microservis2 miz down durumda olursa bu durumda bizim microservis1 mizde bundan negatif etkilenecektir.Dönen hataları handle etsek bile email fonksiyonunu kullanamaz hale gelmiş olacağız.Ya da email servisi cevap dönüyor ancak işlemleri bir şekilde uzadıysa buda performans anlamında bizim de sürelerimizi uzatacaktır,burada bu servisi asenkron çağırsak bile uzayan her çağrı arka planda bir thread blocklayacağı için bizim uygulamamızı olumsuz etkileyecektir.</p><p>Microservisler bağımsız olmayı severler aynı zamanda sistemlerin hataya açık olmamaları için fault toleracinglerinin yüksek olması beklenmektedir.Bu tarz senaryoları yönetmek için asenkron haberleşme patternleri bize bir çözüm alternatifi olarak yol sunmaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*xe-KaJ_xvbaCH05N8oCA6A.png" /></figure><h3><strong>Asenkron İletişim(Asyncronous Communication) Patterni</strong></h3><p>Microservisler birbirleri arasında direkt bağlantı yoktur.Kafka,RabbitMQ yapılar sayesinde microservisler birbirleri arasında bağlantı olmadan haberleşebilirler</p><p>Bu örneğimzide aradaki bağlantıyı sağlamak amacıyla rabbitmq yu kullanacağız.Bu makalede demonuzu yapabilmeniz için gereken sadece temel rabbitmq adımları anlatılmıştır.</p><p><a href="https://www.rabbitmq.com/install-windows.html">https://www.rabbitmq.com/install-windows.html</a> sitesinden install ederek kullanabilirsiniz</p><p>Not:Rabbitmq Windows kurulumu yaparken prerequest olarak erlang istemektedir.Kurdugunuz rabbitmqye göre uygun erlang kurulu olmalıdır.</p><p><a href="https://www.rabbitmq.com/which-erlang.html">https://www.rabbitmq.com/which-erlang.html</a></p><p>Not:Rabbitmq clidan aşağıdaki komutla rabbitmq management console aktif hale getirebilirsiniz</p><p>rabbitmq-plugins enable rabbitmq_management</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*M6FxSQA7pIZLI5EXLx7OYA.png" /></figure><p>Not:İlgili path altında start,stop cli vs gibi bat dosyaları mevcuttur.</p><blockquote>C:\Program Files\RabbitMQ Server\rabbitmq_server-3.9.5\sbin</blockquote><p>Örnek olarak rmq cli da rabbitmqctl.bat list_users çalıştırarak ilgili userlarımızı görebiliriz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*NKH-sste3L2VuE-vDGOuVw.png" /></figure><p>Yukarıdaki adımladan sonra <a href="http://localhost:15672/">http://localhost:15672/</a> adresinden rmq management console giriş yapabiliriz.</p><p>Default username şifre guest — guest dir</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*9GosQ_szZE-ASSvvi7fQaw.png" /></figure><pre>Örneğimiz için öncelikle Exchanges menüsünden EVENTMESSAGE.EXCHANGE adlı bir Exchange yaratıyoruz</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*GDuAkZrOw_f6FdXTg5Bm_A.png" /></figure><p>Daha sonra bir adet DEMO.QUEUE tanımı yapıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*qNqEUHvOvtMcMVxJaq1M_A.png" /></figure><p>Uygulamamızda kullanmak üzere bir user yaratıp ona hak vermemiz gerekiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*pWgJup6mquj34bsFOIE42g.png" /></figure><p>Son olarak da bu Exchange gelen mesajlarımızın kuyruğumuza aktarabilmesi için binding ayarlarını yapıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*bZ1QewDZI9WboADeWGbVdw.png" /></figure><p>Yukarıdaki Customer ve Email microservislerimiz birbirleri ile kuyruk yapısı üzerinden haberleşebilir.Customer microservisimiz kuyruğa email gönderimi için bir event bırakacaktır.Daha sonra bu kuyruğu dinleyen email microservisimiz ise bu kuyruktaki dataları okuyup işlemini yapacaktır.Bu designde email microservisi kapalı olsa bile açıldığında kuyruktan dataları okuyup işleyebilecğei için customer microservisi burda bir hizmet kaybı yaşamaz.Email microservisinin süreleri uzasa bile yine customer microservisi bundan etkilenmeyecektir.</p><p>Şimdi bu designin implemantasyonu için öncelikle Customer Microservisimizden rabbitmq ya data bırakma için bir örnek oluşturalım</p><p>Pom.xmlimize aşağıdaki dependecy ekliyoruz</p><blockquote>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;<br> &lt;/dependency&gt;</blockquote><p>Application.properties dosyamıza ise rabbitmq için gerekli bilgileri ekliyoruz.</p><p>(Autoconfigure kapatılıp istenilirse bu bilgiler koddanda verilebilir.)</p><pre><em># RabbitMQ host<br> </em>spring.rabbitmq.host=localhost<br> <em># Login to authenticate against the broker.<br> </em>spring.rabbitmq.password=DEMO.USER<br> spring.rabbitmq.username=DEMO.USER<br> spring.rabbitmq.port=5672</pre><p>Son olarak da RabbitTemplate yardımıyla datamızı rabbitm ya bırakıyoruz.</p><pre>@RestController<br> public class CustomerController {<br> <br> @Autowired<br> private RabbitTemplate rabbitTemplate;<br> <br> @PostMapping(path = “api/customer”,consumes = MediaType.<em>APPLICATION_JSON_VALUE</em>)<br> public ResponseEntity createCustomer(@RequestBody Customer request) throws Exception<br> {<br> <em>//TODO Customer Creation process<br> //<br> <br> </em>Email email=new Email();<br> email.setName(request.getName());<br> email.setEmail(request.getEmail());<br> <br> ObjectMapper objectMapper = new ObjectMapper();<br> String rmqmessage= objectMapper.writeValueAsString(email);<br> <br> rabbitTemplate.convertAndSend(“EVENTMESSAGE.EXCHANGE”,”DEMO.QUEUE”,rmqmessage);</pre><pre>return ResponseEntity.<em>ok</em>(“Musteri yaratildi”);<br> }<br> }</pre><p>Rabbitmq arabiriminden datalarımızın kuyruğa geldiğini görebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*CMRcIc_sb7NUEkFOFBPdDA.png" /></figure><p>İkinci aşama olarak ise Email microservisimize bir rabbitmq listener yapısı oluşturalım.</p><p>Pom.xmlimizde amqp dependecymiz olmalı.</p><blockquote>&lt;dependency&gt;<br> &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br> &lt;artifactId&gt;spring-boot-starter-amqp&lt;/artifactId&gt;<br> &lt;/dependency&gt;</blockquote><p>Application.propertiese aşağıdaki bağlantı bilgilerini ekliyoruz.</p><pre><em># RabbitMQ host<br> </em>spring.rabbitmq.host=localhost<br> <em># Login to authenticate against the broker.<br> </em>spring.rabbitmq.password=DEMO.USER<br> spring.rabbitmq.username=DEMO.USER<br> spring.rabbitmq.port=5672</pre><p>Son olarak @RabbitListener annotasyonu ile kuyruğa dinleme yapabiliyoruz.</p><pre>import org.springframework.amqp.rabbit.annotation.RabbitListener;<br> import org.springframework.stereotype.Service;<br> <br> @Service<br> public class EmailListener {<br> @RabbitListener(queues = “DEMO.QUEUE”)<br> public void receive(String in) {<br> <br> System.<em>out</em>.println(“Email gonderildi”);<br> }<br> }</pre><p>Uygulamamız ayaklandığı anda kuyruğa atılan mesajlar okunmaya başlıyor.Buradan sonra istenilen logic ile işlemler yapılabilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*OCQBppr8pMHmSoI7_jA2dw.png" /></figure><p>RabbitMQ management consoleda ise kuyruğun consumerlarında listenerımızı görüyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*gzLzF8cRGvOwELrqO6kMhA.png" /></figure><p>Bonus: Birden fazla consumerla kuyruğu dinlemek istersek tek yapmamız gereken @rabbitlistener annotasyonumuzun concurrency parametresi değiştirmek.</p><pre>@Service<br> public class EmailListener {<br> @RabbitListener(queues = “DEMO.QUEUE”,concurrency = “2”)<br> public void receive(String in) {</pre><p>Ve artık birden fazla consumerla kuyruğu dinleyebiliyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*rrydBBUtm7AyZAeBtkw7qQ.png" /></figure><p>Not: İstenilirse rabbitmq da prefetchcount gibi ayarlar containerfactory tanımları ile yapılabilmektedir.</p><p>Bu şekilde iki microservis birbirinden bağımsız olarak haberleşebilmektedirler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af2d82b51d30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SPRING BOOT İLE KAFKA İÇİN ÖRNEK İMPLEMENTASYONLAR]]></title>
            <link>https://medium.com/@bilgehan.yildiz/spring-boot-i%CC%87le-kafka-i%CC%87%C3%A7i%CC%87n-%C3%B6rnek-i%CC%87mplementasyonlar-a09fc50f8815?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/a09fc50f8815</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Sat, 03 Oct 2020 16:40:14 GMT</pubDate>
            <atom:updated>2020-10-03T16:40:14.687Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhaba arkadaşlar bu yazıda spring boot içerisinden kafkaya okuma ve yazma örnekleri inceliyor olacağız.</p><p>Öncelikli olarak kafkamız ile spring bootumuzun uyumlu olan versiyonlarına göre jar seçimimizi yapmalıyız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*o3Biz9I07j5sO1NLRU1Tbg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/389/1*thfwbKMUgVi8MR79bR3kLQ.png" /></figure><p>Kafkaya mesaj yollamak için Öncelikle producer ayarlarını yapmalıyız.Burada da spring içerisinden gelen DefaultKafkaProducerFactory classından faydalınıyor olacağız</p><p>Daha sonra spring boot içerisindeki KafkaTemplate yardımı ile datalarımızı kafkaya gönderebiliriz.</p><p>Kafkanın kendi kütüphanelerinde bulunan producer ile alakalı ayarlara kafkanın dokümantasyonundan ulaşabiliriz(</p><p><a href="https://kafka.apache.org/documentation/#producerconfigs">https://kafka.apache.org/documentation/#producerconfigs</a></p><p>)</p><p>Temel olarak 4 temel ayara ihtiyacımız bulunmaktadır.Diğer ayarlar opsiyonel olarak ihtiyaca göre eklenebilir(Buradada bu özellikleri eklerken kafkanın kendi core kütüphanesinden gelen ProducerConfig classı bu propertylerin ne olduğu konusunda bizi yönlendiriyor olacaktır.)</p><p><strong>KeySerializer:</strong>Key propertimiz için serializer sınıfının hangi implementasyon classı ile yapılacağını belirtir. org.apache.kafka.common.serialization.Serializer interfaceinden türemelidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*L68P1xNWGHZXBB-9I79NcA.png" /></figure><p><strong>ValueSerializer:</strong> value propertimiz için serializer sınıfının hangi implementasyon classı ile yapılacağını belirtir. org.apache.kafka.common.serialization.Serializer interfaceinden türemelidir.</p><p>org.apache.kafka.common.serialization.Serializer</p><p><strong>BootstrapServer:</strong>Kafkamızın koştuğu sunucu bilgisi ve port bilgisini içerir</p><p><strong>ACKS</strong>:Acknowledgement bilgisini içerirAcks=0,tamamen asenkron calısma kafka mesajı gönderir ama ulaşıp ulaşmadığı ile ilgilenmez(Mesaj garantisi yok)</p><p>Acks=1,kafka leader brokerdan ack bekler(Kısmi mesaj kaybı riski,insync replicalardan dolayı) Default değeri budur.</p><p>Acks=all (veya -1) ,kafka leader ve insync replicalar arasındaki tüm işlemlerin bitişine göre ack iletir(insync replicalardan en az biri hayatta olduğu müddetce Mesaj kaybı riski yok)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*Qjt2kWeC2mi_tfMwcTPNFQ.png" /></figure><p>Öncelikli olarak kafka producer ayarlarımızı yapıyoruz</p><p><a href="https://docs.spring.io/spring-kafka/api/org/springframework/kafka/core/DefaultKafkaProducerFactory.html">https://docs.spring.io/spring-kafka/api/org/springframework/kafka/core/DefaultKafkaProducerFactory.html</a></p><pre>@Configuration<br> public class KafkaProducerConfig<br> {<br> <br> @Value(“${kafka.bootstrap-servers}”)<br> private String bootstrapServers;<br> <br> @Bean<br> public Map&lt;String, Object&gt; producerConfigs() {<br> Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();<br> props.put(ProducerConfig.<em>BOOTSTRAP_SERVERS_CONFIG</em>,<br> bootstrapServers);<br> props.put(ProducerConfig.<em>KEY_SERIALIZER_CLASS_CONFIG</em>,<br> StringSerializer.class);<br> props.put(ProducerConfig.<em>VALUE_SERIALIZER_CLASS_CONFIG</em>,<br> StringSerializer.class);<br> props.put(ProducerConfig.<em>ACKS_CONFIG</em>,”all”);<br> return props;<br> }<br> <br> @Bean<br> public ProducerFactory&lt;String, String&gt; producerFactory() {<br> return new DefaultKafkaProducerFactory&lt;&gt;(producerConfigs());<br> }<br> <br> @Bean<br> public KafkaTemplate&lt;String, String&gt; kafkaTemplate() {<br> return new KafkaTemplate&lt;&gt;(producerFactory());<br> }<br> }</pre><pre>@Service<br><br>public class KafkaMessageSenderService {<br><br><br><br>    @Autowired<br><br>    private KafkaTemplate&lt;String, String&gt; kafkaTemplate;<br><br><br><br>    @Value(&quot;${kafka.topic}&quot;)<br><br>    private String kafkaTopic;<br><br><br><br>    public void send(String message) {<br><br><br><br>        kafkaTemplate.send(kafkaTopic, message);<br><br>    }<br><br><br><br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*QNej016MTg_3_XBj5P1CAA.png" /></figure><pre>@RestController<br><br>public class SampleController {<br><br><br><br>    @Autowired<br><br>    KafkaMessageSenderService kafkaMessageSenderService;<br><br><br><br>    @RequestMapping(method = RequestMethod.<em>GET</em>,path =&quot;/sendtokafka&quot; )<br><br>public    String sendMessagetoKafka()<br><br>    {<br><br>        kafkaMessageSenderService.send(&quot;spring to kafka&quot;);<br><br>        return &quot;gonderildi&quot;;<br><br>    }</pre><p>En son restcontrollerımızda yazdığımız sender servisi kullanarak kafkaya mesajı yolluyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*BHHSMafq9xSLMACCG473_A.png" /></figure><p>Kafka consumer cli yardımı ile gönderdiğimiz mesajı kafkada görebildik</p><pre>// KafkaMessageSenderService sınıfına ek key ile gönderim</pre><pre>public void send(String message,String key) {</pre><pre>    kafkaTemplate.send(kafkaTopic,key, message);</pre><pre>}</pre><p>//Key sayesinde aynı keye sahip mesajlar hep aynı partiona giderler</p><pre>@RequestMapping(method = RequestMethod.<em>GET</em>,path =&quot;/sendtokafkawithkey&quot; )<br><br>public    String sendMessagetoKafkaWithKey()<br><br>{<br><br>    kafkaMessageSenderService.send(&quot;spring to kafka with key&quot;,&quot;mykey&quot;);<br><br>    return &quot;gonderildi&quot;;<br><br>}</pre><p>Gönderdiğimiz mesaj kafka cli da yine value seklinde gözüktü.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*KxHMiNWTQ-FhtfJe1trP_g.png" /></figure><p>Son olarak yine KafkaMessageSenderService sınıfımız içeresinde org.springframework.util.concurrent den gelen ListenableFuture metodunu kullanarak kafkadan dönen cevapları da okuyabiliriz.Bu yapı sayesinde kafkaya gönderdiğimiz mesaj fail mi success mi success ise kafkada hangi offset nosu ile yazdı gibi sonuç bilgilerine ulaşabiliriz.</p><pre>public void sendMessageCallback(String message) {<br> <br> ListenableFuture&lt;SendResult&lt;String, String&gt;&gt; future =<br> kafkaTemplate.send(kafkaTopic, message);<br> <br> future.addCallback(new ListenableFutureCallback&lt;SendResult&lt;String, String&gt;&gt;() {<br> <br> @Override<br> public void onSuccess(SendResult&lt;String, String&gt; result) {<br> System.<em>out</em>.println(“Sent message=[“ + message +<br> “] with offset=[“ + result.getRecordMetadata().offset() + “]”);<br> }<br> @Override<br> public void onFailure(Throwable ex) {<br> System.<em>out</em>.println(“Unable to send message=[“<br> + message + “] due to : “ + ex.getMessage());<br> }<br> });<br> }</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*aHnVdC1w_N-vVkBMkSYnTg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*SLWjGSpH6d9f63qcigNYzw.png" /></figure><p>Benzer ayarları bu sefer kafkadan okumak için yapıyoruz yine ProducerConfig ayarlarına benzer ConsumerConfig ayarları,ProducerFactory benzer ConsumerFactory ayarlarını yapıyoruz.</p><pre>@Configuration<br><br>public class KafkaConsumerConfig {<br><br><br><br>    @Value(&quot;${kafka.bootstrap-servers}&quot;)<br><br>    private String bootstrapServers;</pre><pre>@Value(&quot;${kafka.groupid}&quot;)<br> private String groupId;</pre><pre>@Bean<br>     public Map&lt;String, Object&gt; consumerConfigs() {<br>         Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();<br>         props.put(ConsumerConfig.<em>BOOTSTRAP_SERVERS_CONFIG</em>,<br>                 bootstrapServers);<br>         props.put(ConsumerConfig.<em>KEY_DESERIALIZER_CLASS_CONFIG</em>,<br>                 StringDeserializer.class);<br>         return props;<br>     }<br> <br>     @Bean<br>     public ConsumerFactory&lt;String, String&gt; consumerFactory() {<br>         return new DefaultKafkaConsumerFactory&lt;&gt;(consumerConfigs());<br>     }<br> <br>     @Bean<br>     public KafkaListenerContainerFactory&lt;ConcurrentMessageListenerContainer&lt;String, String&gt;&gt; kafkaListenerContainerFactory() {<br>         ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; factory =<br>                 new ConcurrentKafkaListenerContainerFactory&lt;&gt;();<br>         factory.setConsumerFactory(consumerFactory());<br>         return factory;<br>     }<br> }</pre><p>KafkaListenerContainerFactory sayesinde tüm register olan topicleri dinleyebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*UNgJnwEbsJypX9kev_dQpA.png" /></figure><p>setRecordFilterStrategy ilede gelen mesajın içeriğine göre dinleme yapabiliriz.Filter spring diyerek spring içeren mesajların listenerımıza gelmesini engelleyebiliriz.</p><p>Factory filter içeririrse içinde spring olan mesajları filtereleyip diğer mesajların listenera iletilmesini sağlayacaktır.</p><p>@KafkaListener sayesinde farklı listenerlar create edebiliriz.</p><p>Topics kısmına birden fazla topic verebiliriz,ek olarak groupid parametreside vardır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*9Eip3hQxggDQgtKbzOgjNw.png" /></figure><pre>@KafkaListener(topics = “mysample_topic”)<br> @SendTo(“mysample_topic”)<br> String listenAndReply(String message) {<br> <br> return “spring filter ekle message a ekleme yapıp topic 2 ye at”+message;<br> }</pre><p>@KafkaListenera sendto annatosyonu ile bir reply yapısı ekleyebilir.</p><p>Bu örnekte gelen mesajı yine aynı kuyruğa zengişleştirip atıyoruz(Not bu örneği yaparken containerfactory e spring içeren mesajları filterele komutu ekledim aksi takdirde sonsuz döngüye girerdi).</p><p>Çalıştırdığımız zaman “a KafkaTemplate is required to support” hatası alıyoruz bunu aşmak için containerfactoryimize replytemplate eklemeiz gerekiyor.</p><p>Error starting ApplicationContext. To display the conditions report re-run your application with &#39;debug&#39; enabled.</p><p>2020-10-03 17:33:44.397 ERROR 11340 --- [ main] o.s.boot.SpringApplication : Application run failed</p><p>java.lang.IllegalStateException: a KafkaTemplate is required to support replies</p><p>at org.springframework.util.Assert.state(Assert.java:76) ~[spring-core-5.2.8.RELEASE.jar:5.2.8.RELEASE]</p><pre>@Configuration<br> public class KafkaConsumerConfig {</pre><pre>………</pre><pre>//KafkaConsumerConfig class içerisende factory kısmını editliyoruz</pre><pre>@Autowired<br> private KafkaTemplate&lt;String, String&gt; myreplyTemplate;</pre><pre>@Bean<br> public KafkaListenerContainerFactory&lt;ConcurrentMessageListenerContainer&lt;String, String&gt;&gt; kafkaListenerContainerFactory() {<br> ConcurrentKafkaListenerContainerFactory&lt;String, String&gt; factory =<br> new ConcurrentKafkaListenerContainerFactory&lt;&gt;();<br> factory.setConsumerFactory(consumerFactory());<br> <br> factory.setReplyTemplate(myreplyTemplate);<br> factory.setRecordFilterStrategy(<br> record -&gt; record.value().contains(“spring”));<br> return factory;<br> }</pre><p>Şuana kadar yaptığımız listener örnekleri her zaman yeni mesaj geldiğinde okuma yapıyordu peki topici baştan sona okumak istersek ne yapmalıyız.</p><p>props.put(ConsumerConfig.<em>AUTO_OFFSET_RESET_CONFIG</em>,&quot;earliest&quot;);</p><p>Bunun için consumer.config propertylerinden <em>AUTO_OFFSET_RESET_CONFIG </em>earliest a alabiliriz(Default latest).</p><p>Bunun dışında springin eventdriven yapısından çıkılarak direkt kafkanın çekirdek yapısı kullanarak da geliştirme yapılabilir,aşağıda listener mod olarak değil ancak single read için bir örnek vardır.Dikkat edilmesi gereken burada belirtilen sürede pollama yapıp yapamayacağıdır.</p><pre>@Service<br> public class KafkaPollService {<br> <br> @Value(“${kafka.bootstrap-servers}”)<br> private String bootstrapServers;<br> <br> @Value(“${kafka.topic}”)<br> private String kafkaTopic;<br> <br> @Value(“${kafka.groupid}”)<br> private String groupId;<br> <br> <br> public String PollMessage()<br> {<br> Map&lt;String, Object&gt; props = new HashMap&lt;&gt;();<br> props.put(ConsumerConfig.<em>BOOTSTRAP_SERVERS_CONFIG</em>,<br> bootstrapServers);<br> props.put(ConsumerConfig.<em>KEY_DESERIALIZER_CLASS_CONFIG</em>,<br> StringDeserializer.class);<br> props.put(<br> ConsumerConfig.<em>GROUP_ID_CONFIG</em>,<br> groupId);<br> props.put(<br> ConsumerConfig.<em>KEY_DESERIALIZER_CLASS_CONFIG</em>,<br> StringDeserializer.class);<br> props.put(<br> ConsumerConfig.<em>VALUE_DESERIALIZER_CLASS_CONFIG</em>,<br> StringDeserializer.class);<br> <br> props.put(ConsumerConfig.<em>MAX_POLL_RECORDS_CONFIG</em>,1);<br> props.put(ConsumerConfig.<em>AUTO_OFFSET_RESET_CONFIG</em>,”earliest”);<br> props.put(ConsumerConfig.<em>ENABLE_AUTO_COMMIT_CONFIG</em>,true);<br> KafkaConsumer consumer=new KafkaConsumer(props);<br> <br> consumer.assign( Arrays.<em>asList</em>(<br> new TopicPartition(“mysample_topic”, 0),<br> new TopicPartition(“mysample_topic”, 1),<br> new TopicPartition(“mysample_topic”, 2)));</pre><pre>//burada partionlar yerine subsrice ile topic mantıgıda direkt implemente edilebilir<br> <br> ConsumerRecords&lt;String,String&gt; records= consumer.poll(Duration.<em>ofMillis</em>(1000));<br> consumer.commitSync();<br> <br> String mymessage=””;<br> for (ConsumerRecord records1: records ) {<br> mymessage=records1.value().toString();<br> }<br> return mymessage;<br> }<br> <br> }</pre><p>Yazdıgımız metodları api katmanından çağırmak için örnek apiler…</p><pre>package com.example.demo;<br> <br> <br> import com.example.demo.kafka.KafkaConsumerService;<br> import com.example.demo.kafka.KafkaMessageSenderService;<br> import com.example.demo.kafka.KafkaPollService;<br> import org.springframework.beans.factory.annotation.Autowired;<br> import org.springframework.core.convert.Property;<br> import org.springframework.web.bind.annotation.RequestMapping;<br> import org.springframework.web.bind.annotation.RequestMethod;<br> import org.springframework.web.bind.annotation.RestController;<br> <br> import java.util.Enumeration;<br> import java.util.Properties;<br> <br> @RestController<br> public class SampleController {<br> <br> @Autowired<br> KafkaMessageSenderService kafkaMessageSenderService;<br> <br> @Autowired<br> KafkaPollService kafkaPollService;<br> <br> @RequestMapping(method = RequestMethod.<em>GET</em>,path =”/consumefromkafka” )<br> public String consumeMessagetoKafka()<br> {<br> String readmessage=kafkaPollService.PollMessage();<br> return “okundu”+readmessage;<br> }<br> <br> @RequestMapping(method = RequestMethod.<em>GET</em>,path =”/sendtokafka” )<br> public String sendMessagetoKafka()<br> {<br> kafkaMessageSenderService.send(“spring new”);<br> return “gonderildi”;<br> }<br> <br> @RequestMapping(method = RequestMethod.<em>GET</em>,path =”/callback/sendtokafka” )<br> public String sendAsyncMessagetoKafka()<br> {<br> kafkaMessageSenderService.sendMessageCallback(“spring to kafka callback”);<br> return “gonderildi”;<br> }<br> <br> @RequestMapping(method = RequestMethod.<em>GET</em>,path =”/sendtokafkawithkey” )<br> public String sendMessagetoKafkaWithKey()<br> {<br> kafkaMessageSenderService.send(“to kafka with key 2”,”mykey”);<br> return “gonderildi”;<br> }</pre><pre>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a09fc50f8815" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[APACHE KAFKA KURULUMU VE TEMEL KAVRAMLARI]]></title>
            <link>https://medium.com/@bilgehan.yildiz/apache-kafka-kurulumu-ve-temel-kavramlari-964a13a41315?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/964a13a41315</guid>
            <category><![CDATA[apache-kafka]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Wed, 23 Sep 2020 17:09:25 GMT</pubDate>
            <atom:updated>2020-09-23T17:25:56.383Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>APACHE KAFKA KURULUMU VE TEMEL KAVRAMLARI</strong></p><p>Selamlar arkadaşlar bu makalemiz de kafka ile alakalı olarak temel kavramlar, kafkanın kurulumu(windows bir makine için) ve kafkanın monitoringi konularına değiniyor olacağız.Bu makalenin devam makalesinde ise bir spring boot uygulamasından kafkaya mesaj atma ve okuma işlemlerini yapıyor olacağız.</p><p>Not:</p><p>Bu makaleyi yazmadan önceden kafka ile alakalı olarak udemyiden aşağıdaki eğitimi izledim.Apache Kafka ile ilgileniyorsanız ,güzel bir eğitim içeriği.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*Gfo6IddKs3TIj1UDkL7YaQ.png" /></figure><p><strong>Apache Kafka Nedir?</strong></p><p>Apache kafka dağıtık bir veri akış (stream processing) platformdur. Gerçek zamanlı veri akışlarının işlenmesi için birleşik, yüksek verimli, düşük gecikme süreli bir platform sağlamayı amaçlamaktadır (Wikipedia tanımı).</p><p><strong>Stream processing nedir?</strong></p><p>Verilerin alındığı andan itibaren kısa bir süre içinde sürekli veri akışını sorgulamak ve koşulları hızlı bir şekilde tespit etmek için kullanılan bir programlama paradigmasıdır.</p><p><strong>Kafkayı nerelerde kullanabiliriz?</strong></p><p>Mesajlaşma Sistemleri(Asenkron Mesajlaşma patternlerine uygun olarak)</p><p>Application Loglarını toplama</p><p>Stream Processing(Spark)</p><p>Sistemlerin birbirleri arasındaki bağımlığını azaltma</p><p>Big Data Entegrasyonları</p><p><strong>Kafka Birleşenleri</strong></p><p>· Topic:Topic kayıtların saklandığı ve yayınlandığı kategori adıdır</p><p>· Partitions:Topiclerin içerisinde bir veya birden fazla partition bulunur.Partitionlar sayesinde birden fazla consumerın topicden paralel olarak veri okumasına olanak sağlar.</p><p>· Offset:Offset.Her mesajın partition içerisindeki alığı id olarak düşünebilirz.Bu id incremantal olarak artar.örnek olarak Topic A üzerindeki partion 0 da offset 1 offset 3 ten yazıldığı kafka tarafından garanti edilmediktedir.</p><p>Topic içerisindeki partition ve offset değerleri bize nerde olduğumuzu ve sonraki adımda neyi tüketeceğimizi belirtir.</p><p>· <strong>Broker:</strong>Bir kafka clusterı birden fazla brokerın bir araya gelmesi ile oluşur.Brokerı sunucu olarak düşünebiliriz.Örnek olarak kafka distributed bir mimaride olduğu için bir kafka clusterı içerisinde 3 adet brokerımız olduğunu varsayalım.ve Bir adet topicimiz ve bu topic içeresindede 10 adet partition olduğunu varsayarsak partitionlar her biri bu 3 brokera dağılacaktır.Bir Kafka cluster içerisinde her broker bir bootstrap serverdır,cluster içindeki her broker diğer brokerlara kendi üzerindeki topic,partition bağlantı gibi metadata bilgilerini diğer brokerlarla paylaşır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*xRBAxJSAoLErxFyizaSOQw.png" /></figure><p>Bir cluster içerisinde bir brokera ulaşabilirseniz tüm kalan brokerlara da ulaşabilirsiniz</p><p><strong>Topic Replication:</strong>Kafka clusterında bir brokerda sorun olması durumunda veri kaybını önlemek için brokerlar arasında topicin partitionlarını yedekleyerek hizmet devamlılığı sağlamamız mümkündür.Ancak bu replikasyon yapısını kurarken birden fazla brokera replica olan partitionlar için hangi brokerda lider olduğunu belirtmemiz gerekmektedir.bu sayede leader brokerdaki partitiona gelen datalar diğer brokerdaki partitionlara senkronize olurlar.Bu sync olan replica partitionlarada kafkada ISR(in sync replica) denir.</p><p><strong>Zookeper:</strong>Brokerlar arasındaki kimin lider kimin ISR olacağına karar veren yapıdır.Brokerların yönetimini yapar.Zookeper olmadan kafka calışmaz</p><p><strong>Producers:</strong>Dataları topiclere yazan kısımdır.Producer sayesinde biz kafkaya login olarak mesajımızı bırakırız arka planda hangi broker hangi partitiona yazılacağı otomatik olarak arka planda belirlenir.Producer loadbalance mantığında hangi brokera gideceğini belirtir,Yazma işlemi sırasında herhangi bir message key belirtmezsek bu işlem round robin olarak brokerdaki partitionlara yazar.Ancak bir key gönderirse her zaman aynı partitiona yazar</p><p>Ack0:Producer acknowledgement beklemediği için data kaybı olabilir</p><p>Ack1:Producer lider brokera yazdıktan sonrası ile ilgilenmez</p><p>Acks=all ise producer tüm lider+replica brokerlara yazımı bekler.</p><p><strong>Consumers:</strong>Topic deki datayı okuyan kısımlar.Consumer grouplar ise topic bazında partitionları belli bir workloada göre okuyan yapılardır.Eğer bir topice ait partition sayısından fazla consumer olursa ,kalan consumerlar inaktif duruma geçerler.</p><p><strong>KAFKA KURULUMU</strong></p><p>Kafkanın default portu 9092 dir</p><p>Kafka üzerinde datalar defaultta 7 gün olarak kalır</p><p>Kafka Çalıştırmak için openjdk da kurulumuda yapabilirsiniz</p><p>Kafkanın sitesine girerek öncelikle kurulum dosyalarını indiriyoruz</p><p><a href="https://kafka.apache.org/downloads">Apache Kafka</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*UBxIV7XIU2TYb4ycwXymuQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*s5Jfd9wOgswRKyBI-QnU7A.png" /></figure><p>Kafkayı başlatabilmek için önce zookeeperı ayaklandırmak gerekmektedir.Kafka ile alakalı ayarlar extract ettiğimiz kafka içindeki config klasörü içindedir</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*FrPZOlXRnLg7Nug2w6geyw.png" /></figure><p>Zookeper dosyasında ilk yapmamız gereken şey zookeper için snapshotların tutulacağı directoryi pathi belirlemektir.(Path için folderın slashları ters yazın)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*QHIZolPydHxyOzDg7BwJ6A.png" /></figure><p>Kafka bin\windows içindeki zookeeper-server-start batını zookeeper.propertiesi verecek şekilde start ediyoruz</p><p>C:\kafka_2.13–2.6.0\bin\windows&gt;zookeeper-server-start.bat config\zookeeper.properties</p><p>Not:eğer environment variablelara path tanımı yaparsanız yukarıdaki gibi kısa bir şekilde kullanabilirsiniz aksi takdirde zookeper.propertiesin full pathini yazmanız gerekmektedir</p><p>C:\kafka_2.13–2.6.0\bin\windows&gt;zookeeper-server-start.bat C:\kafka_2.13–2.6.0\config\zookeeper.properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*npjIMQNVq5okqRznIdi2TQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*ii1Osro4yEHkw7S9mJTQwA.png" /></figure><p>Zookeeper default port 2181dir</p><p>Temel kafka ayarları ise config klasörü altındaki server.properties içerisindedir.Örnek olarak log pathini buradan veriyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*Er_CBFdQHtPHYi7l4F7Eqw.png" /></figure><p>Zookeeperı çalıştırdıktan sonra farklı bir komut satırı açarak kafkayı start ediyoruz</p><p>C:\kafka_2.13–2.6.0\bin\windows&gt;kafka-server-start C:\kafka_2.13–2.6.0\config\server.properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*4fUuHkGYQ_JmHo08ZepjrQ.png" /></figure><p><strong>KAFKA CLI(Command Line interface)</strong></p><p>Kafka üzerinde topic create etme vs diğer işlemlerimi kafka cli ile yapabiliyoruz.</p><p>Not:Komutlardaki iki adet çizgi birleşince tek gibi gözüksede iki adet tire işareti vardır komutları denerken dikkat ediniz</p><p>C:\kafka_2.13–2.6.0\bin\windows&gt;kafka-topics.bat — zookeeper 127.0.0.1:2181 — topic mysample_topic — create — partitions 3 — replication-factor 2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/681/1*bxRxvpnftR4kblRofnlt9Q.png" /></figure><p>C:\kafka_2.13–2.6.0\bin\windows&gt;kafka-topics.bat — zookeeper 127.0.0.1:2181 — topic mysample_topic — create — partitions 3 — replication-factor 1</p><p>Broker sayısını arttırmadan replication factor sayısı verirsek hata verecektir o yüzden ilk etapta replication-factor sayısını 1 vererek topicimizi create edebiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*T14pnUs-W7_G9OGDU-SUnw.png" /></figure><p>O yüzden kafka-topics.bate zookeeper adresini verip list komutunu çalıştırırsak oluşmuş olan topiclerin listesini görebiliriz</p><p>C:\kafka_2.13–2.6.0\bin\windows&gt;kafka-topics.bat — zookeeper 127.0.0.1:2181 — list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*zTa-YDGTV9oWXUBE8cniNQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*qSzaHB22OZ8MlS6EskYvBw.png" /><figcaption>describe komutu ilede topicimize ait detay bilgilere erişebiliyoruz</figcaption></figure><p>C:\kafka_2.13–2.6.0\bin\windows&gt;kafka-console-producer.bat — broker-list 127.0.0.1:9092 — topic mysample_topic</p><p>Kafka-console-producer.bat yardımı ile topicimize mesajlar atıyoruz(9092 default kafka portu).ctrl+c diyerek burdan cıkabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*xaJyfanps1PCdqku3ValiA.png" /></figure><p>Yukarıdaki kafka-console-producera –producer-property ack=all diyerek ack bilgisi ekleyebiliriz ack0 da mesaj kaybı riski vardır.</p><p>Benzer şekilde kafkadaki mesajları kafka-console-consumer cli ile okuyabiliriz,aşağıdaki şekilde çalıştırırsak kafkaya her yeni mesaj eklediğimizde son eklenen mesajı alacaktır.</p><p>C:\kafka_2.13–2.6.0\bin\windows&gt;kafka-console-consumer.bat — bootstrap-server 127.0.0.1:9092 — topic mysample_topic</p><p>Yukarıdaki gruba — group grupadı seklinde parametre ekleyip birden fazla consumer çalıştırırsak her yeni gelen mesaj aynı grupadı adına sahip consumer tarafından üzerlerindeki yüke göre okunacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*vqxc7HykAhVtEal02TYpaQ.png" /></figure><p><strong>KAFKA UI MONITORING</strong></p><p>Confluent kafka ,conductor gibi ücretli bir ürünleri kullanmadan kafkayı monitör etmek isterseniz kafdrop bu konuda size yardımcı olabilir.</p><p>Kafdrop uygulamasını docker üzerinden calıstıracabileceğiniz gibi</p><p><a href="https://hub.docker.com/r/obsidiandynamics/kafdrop">https://hub.docker.com/r/obsidiandynamics/kafdrop</a></p><p>Git hubda mevcut olan(https://github.com/obsidiandynamics/kafdrop) repoyu kendinize alarak executable jar seklindede çalıştırabilirsiniz.</p><p>Not:HomeAdvisor reposu altında olan kafdrop java 11 ile çalışmamaktadır.</p><p>java -jar ./target/kafdrop-&lt;version&gt;.jar — zookeeper.connect=&lt;host:port&gt;,&lt;host:port&gt;,… — kafka.brokers=&lt;host:port&gt;,&lt;host:port&gt;,…</p><p>\</p><p>//Not isternirse jar çalıştırılırken broker vs ayarlarıda verilebilir</p><p>C:\kafdrop-master\target&gt;java — add-opens=java.base/sun.nio.ch=ALL-UNNAMED -jar kafdrop-3.28.0-SNAPSHOT.jar</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*zEH_NN1V_AxN4ZJTMyGBfg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*OalNuTnE5_MqwnKL1EXMEA.png" /></figure><p><a href="http://localhost:9000/">http://localhost:9000/</a> gittiğimizde artık default ayarlarla calısan kafkamızda yaratılan topic partition sayısı gibi ayarları görebiliyoruz.Örnek ekrandada yarattığımız mysample_topic bilgilerini görebiliyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*XlreMbOMJdU3YMvwFcK9EA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*S2lwqDFj_ztdw_IkZJv4Vw.png" /></figure><p>Hatta mesaj görüntüleme vs işlemlerinide yine kafdrop sayesinde yapabiliyoruz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=964a13a41315" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ÖRNEK BİR SPRING BOOT REST SERVİS UYGULAMASINI WEBLOGIC ÜZERİNDE HOST ETMEK]]></title>
            <link>https://medium.com/@bilgehan.yildiz/%C3%B6rnek-bi%CC%87r-spring-boot-rest-servi%CC%87s-uygulamasini-weblogic-%C3%BCzeri%CC%87nde-host-etmek-4cac39e18691?source=rss-531df2b5f340------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cac39e18691</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[weblogic]]></category>
            <category><![CDATA[restful-service]]></category>
            <dc:creator><![CDATA[BilgehanYıldız]]></dc:creator>
            <pubDate>Sat, 19 Sep 2020 10:35:20 GMT</pubDate>
            <atom:updated>2020-09-19T11:16:03.527Z</atom:updated>
            <content:encoded><![CDATA[<p>Merhabalar,bu yazımızda örnek bir spring boot uygulamasını weblogic üzerinde ayaklandırmak için gereken ayarlardan bahsedeceğiz.WebLogic geniş kapsamlı bir ürün ,administration yapmak için farklı bir uzmanlaşma gerektirse de bu makale içerisinde weblogic’in temel olarak ne olduğunu ve kendi denemelerinizi yapabilmeniz de amaçlı olarak temel kurulumu konusunda bazı konulara değiniyor olacağız.</p><p><strong>WebLogic Server Nedir?</strong></p><p>· WebLogic Server bir uygulama sunucusudur.Tomcate benzemekle beraber bazı yönlenlerde ondan ayrılır.</p><p>· Tomcat bedavadır,weblogic ise ticari kullanımlarda lisanslıdır.</p><p>· Weblogic Enterprise Java Bean support eder,tomcat etmez.</p><p>· Weblogic transaction management yapar ,tomcat yapmaz</p><p><strong>Web Logic Domain nedir?</strong></p><p>Weblogic kaynaklar grubu (admin server, managed servers,) olarak adlandırılabilir.</p><p><strong>Web Logic Kurulumu</strong></p><p>Öncelikle oracle sitesinden ihtiyaca göre kurulumumuzu indiriyoruz biz burada sadece development amaçlı kullanım yapacağımız için quick installeri indirdik.</p><p><a href="https://www.oracle.com/middleware/technologies/weblogic-server-installers-downloads.html">WebLogic Server 12c (12.2.1), WebLogic Server 11g (10.3.6) and Previous Releases</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*VRDS0i5aRi1gwNoGIvQFpg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*mqikS8TYAZ33l7YUeNWI6w.png" /></figure><p>Weblogic kurmak için öncelikle jdk kurulu olması gerekmektedir.</p><p>Not:lisanslama şekli değiştiği için kurduğunuz jdk versiyonuna dikkat edin</p><p>JDK yı ilk defa kuruyorsanız weblogic install etmeden önce makinenizi restart etmeniz gerekmektedir.</p><p>C:\Users\Bilgehan\Desktop\weblogic\fmw_14.1.1.0.0_wls_lite_quick_Disk1_1of1\wls1411\wlserver\common\bin altında config scriptini çalıştırıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*gTLibI85tcaWMEnxaa7H3Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*qGHHUQuQ-2_qjHMUxKiDcw.png" /></figure><p>Sayfa 3 weblogic admin console için gereken username ve password bilgisi mevcuttur</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*Nu0q4bM5znN17SrnJQG1ag.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*j9dhfbTc2nwxwi6fe0_URA.png" /></figure><p>Development amaçlı olduğu için domain mode development seçiyoruz,production modeda daha fazla güvenlik işlemi mevcuttur</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*z89lYeek8-x4U1M9MYhskg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*nR49hE6MKg8Oby3MrKK6Hw.png" /></figure><p>Kurulumu tamamladıktan sonra admin server url basarsanız açılmayacaktır bunun için kurulum bittikten sonra domainimizi oluşturduğumuz yere startweblogic.sh ını çalıştırmamız gerekmektedir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*M41rHQKGu3RDKbZNB3Mw_A.png" /></figure><p>http://makineadınız:7001/console</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/603/1*AAPTPnKIpDO8jMXbPdG_2w.png" /></figure><p>Ve tekrar admin urline girdiğimizde artık administration consolu görebiliyoruz.7001 weblogic admin console için default portunuzdur.</p><p><a href="https://start.spring.io/">https://start.spring.io/</a> iodan paket tipi war olacak şekilde örnek bir spring mvc projesi oluşturalım</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*yJIRjRaGrnS45Wd5PLHChQ.png" /></figure><p>Oluşan war dosyamızı weblogic admin consoledan →Deployments kısmından install etmemiz gerekli</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*3s1UkTTK_2bUmQhdZyXIPQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*djMIFOw3YoiocX27OsryBQ.png" /></figure><p>Burada spring boot uygulamamız bizim örneğimiz için bir rest api açan bir uygulama olduğu için installation typeda deployment as an application seçmemiz gerekiyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*62_AEP2WzZ7jvWXWZ484WA.png" /></figure><p>Daha sonra next diyerek kullanmak istediğimiz serverı seçiyoruz,burada sadece örnek amaçlı olması dolayısıyla weblogic kurduğunuzda default olarak gelen AdminServer üzerine deploymentımızı yapacağız.(Admin server üzerine bu şekilde reelde deployment yapılmaması önerilmektedir)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*OEFZWa9HLT_M1ZY-D2vLhQ.png" /></figure><p>Next-next finish dedikten sonra war dosyamız aktif duruma geçmeli</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*anS2kLonq96sqJ-5ObfyjA.png" /></figure><p>Not deploy ettiğiniz wara deployment sürecinde ayrı bir isim verebilirsiniz aksi takdirde warın kendi ismiyle deploy olacaktır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*4Ak8xhlQzw58ZvzKK40iaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*YEvjR6cMsGM2jL0tnYqP3w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*Z133GY-S6Fhgb4XgFt_Eag.png" /></figure><p>Eğer geçmiyorsa kendimiz deployment kısmından deploy ettiğimiz warın settinglerini giriyoruz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*th9UCQcTPgqoVnDxTfkUpQ.png" /></figure><p>Bu settinglerden kontrol kısmından deploy ettiğimiz warı seçerek start diyebiliriz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*Xel30cDhW-gqhhqBU9jxaQ.png" /></figure><p>En son ise testing kısmında bizim rest uygulamamızın urli yazmaktadır</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*QCXFweR7dYXPvh_AZvqxPg.png" /></figure><p>Bu url bastığınızda sizi spring uygulamanızın base pathine götürür buraya api pathinizde ekleyerek uygulamanızı calıştırabilirsiniz</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/487/1*zPWvt6RtjCsBsFDV9CHvKg.png" /></figure><p><strong>Spring Rest Servis WebLogic ayarları</strong></p><p>Spring boot uygulamanızı weblogice deploy ederken bazı noktalara dikkat etmelisiniz</p><p>İlk olarak pomda spring boot starter tomcatin scope bilgisi provided diye işaretlenmelidir</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*-Nc4HwjDDQs8VnsBKXBUpg.png" /></figure><p><a href="https://docs.spring.io/spring-boot/docs/1.3.0.M1/reference/html/howto-traditional-deployment.html">https://docs.spring.io/spring-boot/docs/1.3.0.M1/reference/html/howto-traditional-deployment.html</a></p><p>İkinci olarak Servlet classımıza WebApplicationInitializerı implement etmek</p><p>public class ServletInitializer extends SpringBootServletInitializer implements WebApplicationInitializer {<br> <br> @Override<br> protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {<br> return application.sources(DemoApplication.class);<br> }<br> <br> }</p><p>Not: SpringBootServletInitializer zaten WebApplicationInitializer referans almakta ancak spring dökümantasyonu açısından bu şekilde örnek verildi ,weblogic 14 de direkt bu şekilde tekrar WebApplicationInitializer implement edilmese bile ayaklanmaktadır.Farklı noktalardaki bir sorun çıkabileceğini öngörerek spring dokümantasyonuna göre yapmakta fayda var.</p><p>public abstract class SpringBootServletInitializer implements WebApplicationInitializer</p><p>Üçüncü olarak yine spring dökümanını baz alarak spring projemize webapp folderı altına WEB-INF içerisine weblogic.xml koyuyoruz</p><p>Bu dosya yoksa weblogic kendi default ayarları ile uygulamamızı ayaklandırır</p><p>Weblogic.xml dosyası ayarları icin</p><p><a href="https://docs.oracle.com/cd/E13222_01/wls/docs92/webapp/weblogic_xml.html">weblogic.xml Deployment Descriptor Elements</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/1*oh8XN9W_n2mUlZc9GJDDpg.png" /></figure><p>Örnek:</p><p>weblogic.xml yokken <a href="http://10.0.75.1:7001/demo-0.0.1-SNAPSHOT/hello">http://10.0.75.1:7001/demo-0.0.1-SNAPSHOT/hello</a></p><p>weblogic.xml var ve oraya context-root değişkeni koyduk,orda okuduğu context root pathe göre uygulamamızın ayaklanma url değişti</p><p><a href="http://10.0.75.1:7001/demo-bilgehan/hello">http://10.0.75.1:7001/demo-bilgehan/hello</a></p><p>Son olarak bizim uygulamamız Spring restful servis örneği olduğu için dispatcherServlet-servlet.xml dosyasına ihtiyaç duymadan ayağa kalkabilmektedir ancak spring projenize göre bu dosyayıda weblogic için eklemeniz gerekebilmektedir</p><p>@RestController<br> public class SampleController →dispatcherServlet-servlet.xml weblogic için ihtiyaç duyulmamaktadır.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cac39e18691" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>