<?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 Emirhan Baran on Medium]]></title>
        <description><![CDATA[Stories by Emirhan Baran on Medium]]></description>
        <link>https://medium.com/@emir.baran255?source=rss-82ed5684017d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iZoOvnDtYU3JbII2eV6m3w.jpeg</url>
            <title>Stories by Emirhan Baran on Medium</title>
            <link>https://medium.com/@emir.baran255?source=rss-82ed5684017d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:11:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emir.baran255/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[Elasticsearch Explained with Real-Life Example: Why It Beats SQL for Search]]></title>
            <link>https://blog.devops.dev/elasticsearch-explained-with-real-life-example-why-it-beats-sql-for-search-b0b87b0526b3?source=rss-82ed5684017d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0b87b0526b3</guid>
            <category><![CDATA[inverted-index]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[full-text-search]]></category>
            <dc:creator><![CDATA[Emirhan Baran]]></dc:creator>
            <pubDate>Sat, 02 Aug 2025 10:22:10 GMT</pubDate>
            <atom:updated>2025-08-25T13:53:55.585Z</atom:updated>
            <content:encoded><![CDATA[<p>You’ve probably heard a lot about Elasticsearch recently — but what exactly is it, why should we use it, and where does it fit in? If you wonder answers of these questions you are on the right address :)</p><p>Think about an e-commerce marketplace application with more than 10 million customers and more than 250,000 sellers. Billions of product listing and search queries coming every day and we have our application that is saving comments that are coming to products of the sellers in PostgreSQL DB which is an RDBMS.</p><p>Over time, our sellers come with a request like this: I want to see sentiment analysis of all comments on my product lines — identify positive, neutral, negative feedback — and spot standing issues or frequently recurring complaints.</p><p>If we try to use PostgreSQL for this sentiment analysis we would be have performance issues in our queries so it’s perfect time to use ElasticSearch for that because you will do full text search for the comments that are coming to products. But what exactly makes ElasticSearch different from classic RDBMS system? The answer is <strong>full-text search &amp; inverted index</strong>.</p><h4><strong>What is Inverted Index?</strong></h4><p>Let’s think that we are examining a comment for a headhone. There are several review for this product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Il-MQELvP3njakRXPVP2DA.png" /></figure><p>If we were using PostgreSQL, we would have :</p><pre>SELECT * FROM reviews WHERE product= &#39;Headphones&#39; and comment ILIKE &#39;%great sound%&#39;;</pre><p>But the problem is searching for keywords(in our example keywords can be terrible, amazing, good, poor quality…) is very hard in RDBMS. On <strong>10 million rows</strong>, this query could take <strong>several seconds or even minutes</strong>, because PostgreSQL needs to scan every row (a full table scan) to find matches.</p><p>Now let’s consider we were indexing these data in ElasticSearch. Each review becomes a <strong>document</strong>:</p><pre>{<br>  &quot;Review_ID&quot;: 1,<br>  &quot;Product&quot;: &quot;Headphones&quot;,<br>  &quot;Comment&quot;: &quot;These headphones are amazing! Great sound.&quot;<br>},<br>{<br>  &quot;Review_ID&quot;: 2,<br>  &quot;Product&quot;: &quot;Headphones&quot;,<br>  &quot;Comment&quot;: &quot;The sound is okay, but the build feels cheap.&quot;<br>},<br>{<br>  &quot;Review_ID&quot;: 3,<br>  &quot;Product&quot;: &quot;Headphones&quot;,<br>  &quot;Comment&quot;: &quot;Terrible quality. Do not buy.&quot;<br>}</pre><p>Now let’s understand how ElasticSearch handles this</p><p>Elasticsearch <strong>tokenizes</strong> the comment into an <strong>inverted index</strong>:</p><pre>amazing -&gt; [1]<br>great -&gt; [1]<br>sound -&gt; [1, 2]<br>okay -&gt; [2]<br>cheap -&gt; [2]<br>terrible -&gt; [3]<br>quality -&gt; [3]<br>buy -&gt; [3]</pre><p>Now, query:<em> “great sound” :</em></p><p>Elasticsearch looks up great → [1], and sound → [1,2].</p><p>Combines results → Brings Document 1 and Document 2 with the sort of <strong>relevance score</strong>.</p><p><strong>Speed</strong>: On the same dataset (10 million reviews), Elasticsearch typically returns results in <strong>tens of milliseconds</strong> because it uses an <strong>inverted index</strong> for O(1) term lookups, rather than scanning all text.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q4uarGJXvYhbvEDrI7JShw.png" /><figcaption>Classic RBDMS table vs Inverted Index Structure</figcaption></figure><p>An inverted index in Elasticsearch works like the index at the back of a book. It lets you look up a word and instantly find all the pages where it appears. Instead of scanning every row like a traditional SQL database does with a LIKE query (which can be painfully slow on billions of records), Elasticsearch breaks down each document into individual tokens (words) and stores them in this inverted index. For example, if a review says “These headphones are amazing! Great sound,” Elasticsearch will index it as amazing → [1], great → [1], sound → [1]. Another review with “The sound is okay, but the build feels cheap” adds sound → [1,2], cheap → [2]. So when you search for “great sound,” Elasticsearch simply looks up both terms in its index and returns documents 1 and 2 almost instantly-no full table scan, just a lightning-fast dictionary lookup. This is the key reason Elasticsearch outperforms traditional RDBMS for full-text search.</p><h4><strong>Architecture of the ElasticSearch</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4X7CRXyPdzcBHLjIlHoYA.png" /><figcaption>Elastic Search Architecture Schema</figcaption></figure><p>Let’s examine each component of the ElasticSearch together.</p><ul><li><strong>Cluster</strong> → A cluster is a collection of one or more nodes (servers) that together store all the data and provide search and indexing capabilities. The cluster is identified by a <strong>unique name</strong> and manages the distribution of data across nodes.</li><li><strong>Node</strong> → Each node is a single instance of Elasticsearch running on a server. <br>Every node can serve as:<br> — <strong>Coordinator Node:</strong> Handles incoming client requests, routes them to the appropriate nodes (data or master), and aggregates the results before returning them to the client. It does not store data or manage the cluster state. Think of it as the “traffic controller” of Elasticsearch.<br>—<strong>Master Node:</strong> Manages the cluster state, creates or deletes indices, tracks which nodes are part of the cluster, and allocates shards. It does not handle search or indexing operations.<br>— <strong>Data Node: </strong>Stores the actual data and executes search and indexing operations. Most heavy lifting happens here.</li><li><strong>Indices and Shards </strong>→ Data in Elasticsearch is stored in indices (similar to a database in RDBMS). Each index is split into shards for scalability.<br> — <strong>Primary Shards:</strong> Original data partitions. <br>— <strong>Replica Shards:</strong> Copies of primary shards for redundancy and high availability.</li></ul><h4><strong>Advantages of the ElasticSearch</strong></h4><ul><li><strong>Distributed and Scalable</strong> → Handles huge amounts of data by horizontally scaling (adding more nodes). Automatic sharding and replication</li><li><strong>High Availability and Fault Tolerance →</strong> Replicas ensure data redundancy. If a node fails, another node with replica shards can take over.</li><li><strong>Full-Text Search → </strong>Built on Lucene, supports advanced text search features (analyzers, tokenization, relevance scoring).</li><li><strong>Schema-Free</strong> → JSON-Based Stores and retrieves JSON documents. Flexible schema allows dynamic mapping.</li><li><strong>RESTful API </strong>→ Easy to integrate with various applications using HTTP and JSON.</li><li><strong>Open Source with Rich Ecosystem</strong> → Integrates well with Logstash and Kibana (<strong>ELK stack for log analysis and visualization</strong>).</li></ul><p><strong>Real-Life Use Cases of Elasticsearch</strong><br> — E-Commerce Search &amp; Product Discovery<br> — Log &amp; Event Data Analysis (ELK Stack)<br> — Sentiment Analysis &amp; Customer Feedback<br> — Autocomplete &amp; Suggestion Systems<br> — Geospatial Search<br> — Fraud Detection &amp; Security Analytics</p><p><strong>Conclusion</strong><br>Elasticsearch doesn’t replace your relational database — it complements it. If your app needs lightning-fast text search, autocomplete, analytics, or large-scale log analysis, Elasticsearch is a must-have in your tech stack</p><p>💡<strong>Coming Nex</strong>t:<br> If you’re interested in setting up Elasticsearch with Spring Boot, check out my next article which we explore the <strong>integration of Spring Boot with a multi-node Elasticsearch cluster and Kibana. A</strong>lso it includes practical examples of Elasticsearch queries to help you get started.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0b87b0526b3" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/elasticsearch-explained-with-real-life-example-why-it-beats-sql-for-search-b0b87b0526b3">Elasticsearch Explained with Real-Life Example: Why It Beats SQL for Search</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Centralized Configuration Management with Spring Cloud Config Server]]></title>
            <link>https://blog.devops.dev/centralized-configuration-management-with-spring-cloud-config-server-6613414cbb05?source=rss-82ed5684017d------2</link>
            <guid isPermaLink="false">https://medium.com/p/6613414cbb05</guid>
            <category><![CDATA[spring-cloud]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-cloud-config]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Emirhan Baran]]></dc:creator>
            <pubDate>Thu, 29 Aug 2024 06:46:05 GMT</pubDate>
            <atom:updated>2024-08-31T15:33:02.165Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, I would like to start introducing Spring Cloud Config Server and why we use it. Spring Cloud Config offers both server and client-side capabilities for managing externalized configuration in distributed systems. So, how this is possible? I would like to show this in the schema below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dJtS7kMX5YGAtYKiUNhPg.png" /><figcaption>Spring Cloud Config Server Architecture</figcaption></figure><p>There are 3 main components that we need for implementing Spring Cloud Config. We need a client, a config server, and a storage to store our config files(GitHub, Database, Redis Cache Database, Local File System…). We store and read our config files from a centralized location. This gives us an advantage which is <strong>when we make changes in our microservice we don’t need to restart our microservice again, these changes will be applied to our microservices.</strong></p><h3>Why Centralized Configuration?</h3><p>In a distributed system, especially one built on microservices architecture, managing configurations can become complex and challenging. Each service typically requires its own set of configurations, including database connections, API keys, feature flags, and environment-specific settings (e.g., development, staging, production). As the number of services grows, keeping track of all these configurations across multiple environments can quickly become unmanageable. That’s why we should use a centralized configuration.</p><p>Now it’s time for a demo application to see how we can implement it in our projects.</p><h3>Demo Introduction</h3><p>In this demo, we&#39;ll set up a Spring Cloud Config Server using GitHub to store configuration files. We&#39;ll create a microservice named user-ms that retrieves configurations from the Config Server and exposes two endpoints:</p><ol><li><strong>Build Version Endpoint</strong> (/v1/user/build-version): Fetches the build version.</li><li><strong>Contact Info Endpoint</strong> (/v1/user/contact-info): Retrieves contact details.</li></ol><h3>Configuration Files</h3><p>We&#39;ll use two configuration files stored in a GitHub repository:</p><ol><li><strong>user-ms.yml (Default)</strong>: Contains general settings like the build version and contact info.</li><li><strong>user-ms-prod.yml (Production)</strong>: Overrides default settings with production-specific values.</li></ol><p>Github repo link for config files: <a href="https://github.com/emirhanbaran0/e-commerce-config-server/">https://github.com/emirhanbaran0/e-commerce-config-server/</a></p><h3>What We&#39;ll Do</h3><ul><li><strong>Step 1</strong>: Set up the Config Server to fetch configs from GitHub.</li><li><strong>Step 2</strong>: Create the user-ms microservice with two endpoints.</li><li><strong>Step 3</strong>: Demonstrate profile-based configuration for default and prod.</li><li><strong>Step 4</strong>: Test the microservice with different profiles.</li></ul><p>By the end, you&#39;ll see how to manage centralized configurations in a microservices architecture using Spring Cloud Config and GitHub.</p><p><strong>Step 1: Setting Up Config Server</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koVUGtuii_eXbfdcUOP3mw.png" /></figure><p>You can initialize the config-server project like in the image. Then we need to make a few configurations for connecting GitHub and declare this microservice as Spring Cloud Config Server.</p><pre>@SpringBootApplication<br>@EnableConfigServer<br>public class ConfigServerApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(ConfigServerApplication.class, args);<br>    }<br><br>}</pre><p>Here I added @EnableConfigServer to enable this project as Spring Cloud Config Server. After that, we need to set up some configurations in our <em>application.yml</em> file. You can see these config below.</p><pre>server:<br>  port: 8090<br><br>spring:<br>  application:<br>    name: config-server<br>  profiles:<br>    active: git<br>  cloud:<br>    config:<br>      server:<br>        git:<br>          uri: &quot;https://github.com/emirhanbaran0/e-commerce-config-server&quot;  #repository url<br>          default-label: main #default branch<br>          timeout: 5 #should wait until 5 seconds<br>          clone-on-start: true<br>          force-pull: true #reading always the latest config from main branch</pre><p>Our config server is ready to read config files from the GitHub Repository(“<em>https://github.com/emirhanbaran0/e-commerce-config-server</em>&quot;).</p><p>After making the required changes in config-server we are ready to go for step 2.</p><p><strong>Step 2: Creating user-ms</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iLzSmgrwghW5LHqTjvaI8w.png" /></figure><p>You can initialize the <em>user-ms</em> microservice like in the image above. After initializing the user-ms microservice project let&#39;s make the required changes. First, we will configure the<em> application.yml </em>file.</p><pre>spring:<br>  application:<br>    name: user-ms<br>  config:<br>    import: optional:configserver:http://localhost:8090  #config-server url<br>  profiles:<br>    active: default #indicate which profile active<br>server:<br>  port: 8080<br><br>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: refresh </pre><p>These are the required configs for being a client of our config-server. I want to highlight why we use <strong><em>management.endpoints.we.exposure.include=refresh </em></strong>properties. When we have changes in our config files if we want to get the latest values from config-server first we should call <a href="http://localhost:8080/actuator/refresh"><strong>http://localhost:8080/actuator/refresh</strong></a><strong> </strong>endpoint this will allow us to get the latest values of the config file. After that let&#39;s write <strong><em>UserController </em></strong>class.</p><pre>package com.emirhan.baran.user_ms.controller;<br><br>import com.emirhan.baran.user_ms.dto.UserContactInfoDto;<br>import com.emirhan.baran.user_ms.util.GenericResponse;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.beans.factory.annotation.Value;<br><br>import java.util.Map;<br><br>@RestController<br>@RequestMapping(&quot;v1/user&quot;)<br>@RequiredArgsConstructor<br>public class UserController {<br><br>    private final UserContactInfoDto userContactInfoDto;<br>    @Value(&quot;${build.version}&quot;)<br>    private  String buildVersion;<br><br>   <br>    @GetMapping(&quot;/contact-info&quot;)<br>    public GenericResponse getContactInfo(){<br>        return new GenericResponse(200,&quot;User MS contact info&quot;,userContactInfoDto);<br>    }<br><br>  <br>    @GetMapping(&quot;/build-version&quot;)<br>    public GenericResponse getBuildInfo(){<br>        return new GenericResponse(200,&quot;User MS build version&quot;,buildVersion);<br>    }<br><br><br><br>}</pre><p>I have 2 endpoints one will bring the contact info for user-ms and the other one is for getting the build version. I use a dto class for getting contact info. Here is my UserContactInfoDto implementation:</p><pre>package com.emirhan.baran.user_ms.dto;<br><br>import lombok.Getter;<br>import lombok.Setter;<br>import org.springframework.boot.context.properties.ConfigurationProperties;<br><br>import java.util.List;<br>import java.util.Map;<br><br>@ConfigurationProperties(prefix = &quot;user&quot;)<br>@Getter<br>@Setter<br>public class UserContactInfoDto {<br>    String message;<br>    Map&lt;String,String&gt; contactDetails;<br>    List&lt;String&gt; onCallSupport;<br>}</pre><p>For indicating this class will get properties from the config file we need to do use <strong>@EnableConfigurationProperties </strong>annotation in our <em>UserMsApplication class. You</em> can see this in the photo below.</p><pre>package com.emirhan.baran.user_ms;<br><br>import com.emirhan.baran.user_ms.dto.UserContactInfoDto;<br>import org.springframework.boot.SpringApplication;<br>import org.springframework.boot.autoconfigure.SpringBootApplication;<br>import org.springframework.boot.context.properties.EnableConfigurationProperties;<br><br>@SpringBootApplication<br>@EnableConfigurationProperties(value = {UserContactInfoDto.class})<br>public class UserMsApplication {<br><br>    public static void main(String[] args) {<br>       SpringApplication.run(UserMsApplication.class, args);<br>    }<br><br>}</pre><p>After that, we are ready to get config files from the GitHub repository. We have to files in our GitHub repository.</p><p><strong>Step 3 : Creating Config Files For Default and Prod Env</strong></p><ol><li>user-ms.yml File(Default Config File)</li></ol><pre>build:<br>  version: &quot;1.0.1&quot;<br><br>user:<br>  message: &quot;Welcome to MicroShop user related local APIs&quot;<br>  contact-details:<br>    name: &quot;Emirhan Baran- Developer&quot;<br>    email: &quot;emir.baran255@gmail.com&quot;<br>  on-call-support:<br>    - 05144305129<br>    - 21324211123</pre><p>2- user-ms-prod.yml File(Prod related info Config File)</p><pre>build:<br>  version: &quot;1.0.0&quot;<br><br>user:<br>  message: &quot;Welcome to MicroShop accounts related prod APIs&quot;<br>  contact-details:<br>    email: &quot;emir.baran25@gmail.com&quot;<br>  on-call-support:<br>    - 05144305128<br>    - 21324211123</pre><p>You can visit the repo with this link: <a href="https://github.com/emirhanbaran0/e-commerce-config-server">https://github.com/emirhanbaran0/e-commerce-config-server</a></p><p>Now let’s first start config-server microservice and then user-ms microservice and try to send requests endpoints(<em>contact-info, build-version</em>) in the UserController class.</p><p>Remember that in our user-ms file active profile is default. You can see that in user-ms application.yml file value of<strong><em> spring.profiles.active=default </em></strong>that’s why we need to expect to get values from the default config file.</p><p><strong>Step 4: Testing the demo application</strong></p><p>Sending request to /contact-info endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L_a46HFNjGmso1EQ6PaWgQ.png" /></figure><p>Sending request to /build-version endpoint:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hs_scTanPUcowIZDCET3tA.png" /></figure><p>After that I am going to change active profile to prod env in application.yml file of user-ms.<br>Updated application.yml file:</p><pre>spring:<br>  application:<br>    name: user-ms<br>  config:<br>    import: optional:configserver:http://localhost:8090  #config-server url<br>  profiles:<br>    active: prod #changed active profile to prod env<br>server:<br>  port: 8080<br><br>management:<br>  endpoints:<br>    web:<br>      exposure:<br>        include: refresh</pre><p>Then I will send 2 requests again.</p><p>Sending request to /contact-info while in prod profile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHElNnyBCFinid4ebVJtGw.jpeg" /></figure><p>You can see that when we change the profile, our client started to get properties from prod related config file.</p><p>Sending request to /build-version while in prod profile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TFebWZgSs5rNWyNreztwAw.jpeg" /></figure><p>You can notice that when we send the request to /build-version our version changed “1.0.1” to “1.0.0&quot; it’s because in the <strong>user-ms-prod.yml</strong> file value of <em>build.version</em> properties is “1.0.0&quot;.</p><p><strong>Conclusion</strong></p><p>Centralized configuration management is crucial for maintaining consistency, security, and efficiency in a microservices architecture. By leveraging Spring Cloud Config Server, you can externalize your configurations and manage them from a central location like a GitHub repository. This approach not only simplifies configuration management but also allows your microservices to dynamically adapt to different environments without manual intervention.</p><p>In this article, we’ve demonstrated how to set up a Spring Cloud Config Server, create a microservice client (user-ms), and manage different configurations for different environments (default and prod). With this knowledge, you can now streamline your configuration processes, reduce errors, and enhance the agility of your microservices deployments.</p><p>Start implementing centralized configuration in your projects and experience the benefits of a well-organized and easily maintainable system configuration!</p><p><strong>Contact Me:</strong></p><p><strong><em>Github:</em></strong> <a href="https://github.com/emirhanbaran0">https://github.com/emirhanbaran0</a><br><strong><em>Linkedin:</em></strong> <a href="https://www.linkedin.com/in/emirhanbaran0/">https://www.linkedin.com/in/emirhanbaran0/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6613414cbb05" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/centralized-configuration-management-with-spring-cloud-config-server-6613414cbb05">Centralized Configuration Management with Spring Cloud Config Server</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Security’nin Arkasındaki Sihir: Spring Security Mimarisi]]></title>
            <link>https://medium.com/@emir.baran255/spring-securitynin-arkas%C4%B1ndaki-sihir-spring-security-mimarisi-f1a7cb4b73ba?source=rss-82ed5684017d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1a7cb4b73ba</guid>
            <dc:creator><![CDATA[Emirhan Baran]]></dc:creator>
            <pubDate>Thu, 25 Apr 2024 06:55:48 GMT</pubDate>
            <atom:updated>2024-04-25T06:55:48.390Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu yazımda Spring Security mimarisini ve uygulamalarınızı Spring JWT(JSON WEB TOKEN) ve Cookies konularında rehberlik yapacağım.Öncelikle bu yazıyı kaleme almamdaki en büyük sebeplerden biri çok fazla Türkçe kaynak olmamasıdır. Bu nedenle herkese yararlı olmasını diliyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yYv_d0Fv58eDIplx.png" /></figure><p>Öncelikle Security için çok önemli olan ve birbirleri ile çok karıştırılan <strong>Authentication </strong>ve <strong>Authorization </strong>kavramlarına açıklık getirerek başlayalım.</p><p><strong>Authentication</strong>: Kullanıcıların kimliklerini doğrulanmasına ve onaylanmasına yönelik işlemleri içerir. Bu çeşitli yollar ile gerçekleşebilir. Örneğin bir web sitesine girerken kullanıcı adı şifre girilmesi, parmak izi ile telefon kilidinin açılması gibi süreçler bir authentication sürecidir.</p><p><strong>Authorization:</strong> Uygulamanıza gele bir kullanıcının hangi kaynaklara(sistem, dosya, klasör, web sayfası vb.) ulaşabileceğini belirleyen süreçtir.</p><p>Bu kavramları anladıktan sonra şimdi ise bir authentication yöntemi olan JWT(JSON WEB TOKEN) nedir? bu konuya bir açıklık getirelim.</p><p><strong>JWT(JSON WEB TOKEN): </strong>Security süreçlerinde authentication ve authorization için kullanılabilen bir JSON nesnesidir. Server ve client arasında güvenli bir veri aktarımı olmasını sağlar. Server bir JWT token oluşturur ve kullanıcı istekleri atarken bu JWT tokeni kullanır, bu sayede server bu kullanıcıyı tanıyarak isteklerine cevap verir. JWT aşağıda görüldüğü gibi header, payload ve signature olmak üzere üç kısımdan oluşur.</p><p><strong>Header</strong>: JWT oluşturmak için kullanılan algoritmanın bulunduğu kısımdır.</p><p><strong>Payload</strong>: Custom olarak özelleştirebileceğimiz, istediğimiz verileri ekleyip çıkarabileceğimiz kısmı içerir. (Genelde kullanıcıya ve token’a ait bilgileri içerir.)</p><p><strong>Signature</strong>: JWT token oluştururken ve gelen jwt’yi çözerek kullanıcı bilgilerini alabileceğim bir imza string’i içerir. Bu kısım JWT token oluşturmak ve çözmek için çok önemlidir</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z2hTB-R41DY9FcozOFAUpQ.png" /><figcaption>JWT Token ve Token Kısımları İçin <a href="https://jwt.io/">https://jwt.io/</a> Sitesinden Bir Örnek</figcaption></figure><p><a href="https://jwt.io/">https://jwt.io/</a> sitesinden bazı denemeler yaparak JWT yapısını inceleyebilirsiniz.</p><p>JWT’den farklı olarak birde <strong>cookie</strong>’ler ile authentication ve authorization işlemleri uygulanabilir.Şimdi ise cookielerin nasıl çalıştığını anlayacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xDu1x7JrbronxOyP0KTZBA.jpeg" /><figcaption>Authentication With Cookies</figcaption></figure><p>Kullanıcıların her sayfa yüklendiğinde kullanıcı adı ve şifre gibi kimlik bilgilerini yeniden girmek zorunda kalmaması için cookie’ler kullanılır.Genellikle kullanıcılar bir form login sistemi üstünden kullanıcı bilgilerini girerler ve bunun sonucunda HTTPSession ve cookie oluşur. Cookie içinde kullanıcının sistem tarafından tanınması gibi bazı bilgiler tarayıcı içinde saklanır ve server kullanıcıdan gelen istekleri bu sayede tanıyarak özel kaynaklara erişim verebilir. Cookie’ler genellikle Web uygulamalarında tercih edilirken. Jwt ise daha çok mobil uygulamalarda authentication ve authorization için tercih edilir.</p><p><strong>Not: </strong>Kötü niyetli kişiler tarafından cookie’leriniz ele geçirilirse onlar sisteme sizmişsiniz gibi istek gönderebilir. Bunu önlemek için csrf token’lar kullanılabilir.Bu konu hakkında daha detaylı bilgi için <a href="https://burak95.medium.com/csrf-nedir-3ac7cd51488b">https://burak95.medium.com/csrf-nedir-3ac7cd51488b</a> yazısını okuyabilirsiniz</p><p><strong>JWT Token vs Cookies</strong></p><p><strong>JWT TOKEN Avantajları</strong></p><ul><li><strong>Durumdan Bağımsızlık (Stateless):</strong> JWT tokenlar sunucu tarafında oturum bilgisini saklamaya ihtiyaç duymaz, bu da uygulamanın ölçeklenebilirliğini artırır. Her istekte kullanıcı kimliği ve yetkiler token içinde saklanır. Stateless olması yatay ölçeklemeyi destekler.</li><li><strong>Güvenlik:</strong> Güvenli bir şekilde şifrelenmiş ve imzalanmıştır, bu da JWT’lerin değiştirilmesini veya sahteciliğini zorlaştırır.</li><li><strong>Esneklik:</strong> Farklı uygulamalar arasında kolayca taşınabilir, örneğin mobil uygulamalar ve web uygulamaları arasında.</li></ul><p><strong>JWT Token Dezavantajları:</strong></p><ul><li><strong>Token Boyutu</strong>: JWT’ler genellikle cookie’lere göre daha büyük boyutludur, bu da ağ üzerinden daha fazla veri gönderilmesi gerektiği anlamına gelir.</li><li><strong>Yenileme Sorunu:</strong> JWT’lerin süresi dolduğunda, otomatik olarak yenilenemezler; bu kullanıcıya yeniden giriş yaptırabilir veya karmaşık yenileme mekanizmaları gerektirebilir.</li><li><strong>XSS ve CSRF Güvenlik Riskleri:</strong> Eğer tokenler client-side saklanırsa, Cross-Site Scripting (XSS) saldırılarına maruz kalabilir.</li></ul><p><strong>Cookies Avantajları:</strong></p><ul><li><strong>Kullanım Kolaylığı</strong>: Tarayıcılar cookie’leri otomatik olarak yönetir ve her istekle birlikte gönderir. Bu, geliştiriciler için ekstra iş yükünü azaltır.</li><li><strong>Oturum Yönetimi</strong>: Sunucu tarafında oturumların yönetilmesi, kullanıcıların oturum süresini kolayca kontrol etme ve oturumları gerektiğinde sonlandırma olanağı sunar.</li><li><strong>Güvenlik Özellikleri</strong>: HttpOnly ve Secure bayrakları, cookie’lerin sadece HTTP üzerinden erişilebilir olmasını ve sadece şifreli bağlantılar üzerinden gönderilmesini sağlar.</li></ul><p><strong>Cookies Dezavantajları:</strong></p><ul><li><strong>Ölçeklenebilirlik Sorunları</strong>: Durumlu (stateful) olması, yüksek trafikli uygulamalarda ölçeklenebilirlik sorunlarına yol açabilir çünkü her kullanıcı için sunucu tarafında oturum bilgisi tutulması gerekir. Stateless olması yatay ölçeklemeyi desteklemez.</li><li><strong>CSRF Saldırıları</strong>: Cookie’ler, Cross-Site Request Forgery (CSRF) saldırılarına karşı savunmasız olabilir. Bu, saldırganların kullanıcıların bilgisi dışında istekler göndermesine yol açabilir.</li><li><strong>Tarayıcı Kısıtlamaları</strong>: Bazı durumlarda, tarayıcılar veya kullanıcılar tarafından cookie’ler engellenebilir veya kısıtlanabilir.</li></ul><h3>Hangisi Ne Zaman Kullanılmalı?</h3><ul><li>JWT kullanımı, API’ler arası iletişimde veya farklı cihazlardan (mobil, web, diğer uygulamalar) erişim gerektiren durumlarda tercih edilmelidir.</li><li>Cookie tabanlı kimlik doğrulama, web uygulamalarında daha klasik bir kullanıcı deneyimi sunmak ve sunucu tarafında kullanıcı oturumlarını yönetmek için uygundur.</li></ul><p>Şimdi ise Spring Security için önemli bazı kavramlardan bahsedelim. Spring Mimarisini içeren bir fotoğraf üzerinden kavramları anlayacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iY3bHI4VXeYSOXXE.png" /><figcaption><a href="https://www.javadevjournal.com/spring-security/spring-security-authentication/">https://www.javadevjournal.com/spring-security/spring-security-authentication/</a> (Spring Security Mimarisi)</figcaption></figure><p>Bu fotoğraf Spring Security mimarini anlatmak için çok açıklayıcı ve popüler olan bir fotoğraftır.</p><p>Burada hikaye kullanıcımızın bir istek(request) göndermesi ile başlıyor. Kullanıcımız isteğini gönderdikten sonra kullanıcının isteği controller’a ulaşmadan önce çeşitli aşamalardan geçiyor ve istek buna göre şekillenip bir cevap dönülüyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/0*ZsieEwZ2Y6ZEHuIl" /><figcaption>Security Filter Chain</figcaption></figure><p>Spring mimarisine baktığımızda kullanıcı bir istek attığında istek ilk olarak <strong>Security Filter Chains</strong>’ten geçiyor. Peki nedir bu Security Filter Chains? Security filter Chains kullanıcı bir istek gönderdiği zaman bu isteği çeşitli filtrelerden geçirerek uygulamamızın güvenliğini sağladığımız yerdir. Buraya Spring Security tarafından bize sunulan ve özelleştirebileceğimiz çeşitli filtreleri ekleyebiliriz. Bunlardan bazıları şu şekildedir.</p><p><strong>JWT Authentication Filter: </strong>JSON web token kullanarak authentication yapmamızı sağlayan filtredir. Örneğin bu filtreyi Security Filter Chain’e eklediğimizde gelen istek bu filtreden geçerken uygun bir JWT token bulunduruyorsa ve diğer filtrelerden de geçtiyse server’da bulunan kaynağa(API’ye) ulaşabilir ve buradan bir cevap alabilir. Eğer token yoksa veya token uygun değilse kullanıcının isteği geri çevrilir.</p><p><strong>UseranamePasswordAuthenticationFilter: </strong>Bu filtre genellikle form tabanlı kimlik doğrulama için kullanılır. Kullanıcı adı ve şifre içeren kimlik doğrulama isteklerini işler. Kullanıcı adı ve şifre, HTTP isteği içinde gönderilir ve eğer sistemde bulunan bir kullanıcının bilgileri ile eşleşiyorsa isteğin bu filtreden geçmesine izin verilir.</p><p>Bunun gibi farklı filtreler Spring Security tarafından bizlere sunulmaktadır. Uygulamamız için en uygun olanı veya olanları seçmek bizim için avantajlı olacaktır.</p><p>İsteğimiz filter chain’e ulaştıktan sonra bu filtrelerden geçmesi için bir authentication süreci olması gerekir. Bu authentication süreci <strong>AuthenticationManager </strong>tarafından yönetilir.</p><p><strong>AuthenticationManager</strong>: Filtreden istek alındığında, kullanıcı bilgilerinin doğrulanması işlemini <strong>AuthenticationProvider</strong>’lara devreder. Bir uygulamanın içinde birden fazla <strong>AuthenticationProvider </strong>olabileceğinden, mevcut tüm <strong>AuthenticationProvider’ları </strong>yönetmek AuthenticationManager’ın sorumluluğundadır.</p><p>Akla gelen ilk soru nedir bu <strong>Authentication Provider</strong>? Bu soruya şu şekilde cevap verebiliriz: <strong>Authentication Provider, </strong>kimlik doğrulama için kullanıcı bilgilerini doğrulama sürecindeki kuralları belirlediğimiz yerdir. Örneğin Spring Security’nin bize sunduğu Authentication Provider’lardan biri olan <strong>DaoAuthentication </strong>provider kullanıcının bilgilerini(kullanıcı adı, şifre, hesabın aktif olup olmadığı gibi bilgiler) database’den getirerek kullanıcının doğrulanmasını sağlar. Örneğin kullanıcı username ve şifresini girdikten sonra DaoAuthentication veritabanına gider ve kullanıcının bilgilerini getirir ve bilgilerin doğru olup olmadığına bakar, daha sonra eğer kullanıcı adı ve şifre bilgileri doğru ise bu filtreden geçmesine izin verir eğer doğru değilse isteği controller’a ulaşmadan geri çevirir. Bu bilgileri database’den getirirken <strong>UserDetails </strong>interface’i ile <strong>UserDetailsServis</strong> interface’ini kullanır.</p><p><strong>UserDetails: </strong>Kullanıcıya ait güvenlik bilgilerini içeren metotları içeren bir interface’tir.</p><pre>public interface UserDetails extends Serializable {<br>    Collection&lt;? extends GrantedAuthority&gt; getAuthorities();<br><br>    String getPassword();<br><br>    String getUsername();<br><br>    boolean isAccountNonExpired();<br><br>    boolean isAccountNonLocked();<br><br>    boolean isCredentialsNonExpired();<br><br>    Boolean isEnabled();<br>}</pre><p>Bu interface’i implement eden sınıflar bu metotları kendi logic’lerine göre implement etmelidir.</p><p><strong>UserDetailsService: </strong>Kullanıcı ait bilgilerin DB sistemlerinden alınmasına yardımcı olur.</p><pre>public interface UserDetailsService {<br>    UserDetails loadUserByUsername(String username) throws UsernameNotFoundException;<br>}</pre><p>Yukarıda görüldüğü gibi bu interface bir tane metot içerir ve bu metot kullanıcı adı verilen kullanıcının bilgilerinin databaseden getirilmesini ifade eder.</p><p>Şimdi tüm bu yaptıklarımızı özetleyecek olursak gelen bir istek öncelikle controller’dan önce Security Filter Chain’e gelir ve buradaki filtrelerden geçerek controller’a ulaşmaya çalışır. Bu filtrelerden geçmesi için AuthenticationManager tarafından yönetilen AuthenticationProvider’ların istediği şartları sağlaması gerekir.Eğer gelen istek şartları sağlıyorsa filtrelerden geçerek controller’a ulaşır ve istediği cevabı alır. Aksi bir durumda istek controller’a ulaşmadan kesilmiş olur.</p><p><strong>Not</strong> : Şifreler database’e direkt olarak kaydedilmez çeşitli algoritmalara kullanarak encrypt ederek şifreli bir şekilde kaydedilir bu da verilerin güvenliğini sağlar.</p><p>Bu serinin devamı olarak <strong>Spring Boot 3 ve Spring Security 6 </strong>kullanarak uygulamalı bir şekilde demo uygulaması yapıp github reposu(repoya iletişim kısmındaki github profilinden ulaşabilirsiniz) olarak ekleyeceğimi, ayrıca uygulanmasını anlatacağım bir yazıyı da kaleme alacağım bu yazıyı da yakın zamanda profilimde bulabilirsiniz.</p><p>Keyifli Çalışmalar :))</p><p><strong><em>İletişim</em></strong></p><p><strong>Email</strong>: emir.baran255@gmail.com</p><p><strong>LinkedIn</strong>: <a href="https://www.linkedin.com/in/emirhanbaran0/">https://www.linkedin.com/in/emirhanbaran0/</a></p><p><strong>Github</strong>: <a href="https://github.com/emirhanbaran0/">https://github.com/emirhanbaran0/</a></p><p><strong><em>Kaynaklar</em></strong></p><ul><li><a href="https://medium.com/@tanmaysaxena2904/spring-security-the-security-filter-chain-e09e1f53b73d">https://medium.com/@tanmaysaxena2904/spring-security-the-security-filter-chain-e09e1f53b73d</a></li><li><a href="https://chat.openai.com/">https://chat.openai.com/</a></li><li><a href="https://www.youtube.com/watch?v=7ej-cWEGKwc">https://www.youtube.com/watch?v=7ej-cWEGKwc</a></li><li><a href="https://www.javadevjournal.com/spring-security/spring-security-authentication/">https://www.javadevjournal.com/spring-security/spring-security-authentication/</a></li><li><a href="https://erhankocabuga.com/json-web-token-jwt-nedir">https://erhankocabuga.com/json-web-token-jwt-nedir</a></li><li><a href="https://burak95.medium.com/csrf-nedir-3ac7cd51488b">https://burak95.medium.com/csrf-nedir-3ac7cd51488b</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1a7cb4b73ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Springboot ile RabbitMQ]]></title>
            <link>https://medium.com/@emir.baran255/springboot-ile-rabbitmq-eba677292a0e?source=rss-82ed5684017d------2</link>
            <guid isPermaLink="false">https://medium.com/p/eba677292a0e</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Emirhan Baran]]></dc:creator>
            <pubDate>Mon, 30 Oct 2023 14:52:06 GMT</pubDate>
            <atom:updated>2024-01-07T08:53:30.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*egwQl2YAwkUa5OQdzVrwAw.jpeg" /></figure><p>Veri miktarının müthiş bir hızla arttığı günümüzde bu yapılan uygulamalardaki kullanılan mimarinin de değişmesine neden olmaktadır. Bu mimarilerden biri ise mikroservis mimarisidir. Monolitik mimarinin aksine bu mimari çeşidinde bir uygulama kendi içinde diğer uygulama parçalarına dönüşür fakat burada önemli bir sorun ortaya çıkmakadır. Bu uygulama parçaları kendi aralarında nasıl organize oluyor, bir bütün halinde hareket edebiliyor? Burada ise karşımıza <strong>RabbitMQ</strong>,<strong> Apache Kafka</strong> mesaj işleme yazılımları(<strong>Message Broker</strong>) yardımımıza koşuyor. Sadece bu konuda değil farklı sunucular arasındaki iletişimi sağlayarak büyük ölçekli, dağıtılmış sistemlerin oluşturulmasına, işlerin sırayla işlenmesine ve önceliklendirilmesine, günlük(log) verilerini toplama ve merkezi bir konumda saklaması gibi konularda da kullanılabilir.</p><p>Bu yazımda ise sizlerle beraber spring ile rabbitmq entegrasyonunu producerlar oluşturup, bu producerlar ile oluşturduğumuz kuyruklara mesajlar(String ve Json) yollayacağız ve yine beraber oluşturacağımız farklı consumerlar ile bu mesajları ilgili kuyruklardan okuyacağız. Fakat öncelikle sizlere yukarıda bahsettiğim kafanızı karıştıran bazı temel RabbitMQ konseptlerinden bahsetmek istiyorum. (<em>Producer,Consumer,Queue,Exchange,Binding,Routing Key</em>)</p><p><strong>RABBİTMQ TEMEL KONSEPTLER</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*X92kvKdzUE6ZKBA_UZ0RlA.jpeg" /><figcaption>RabbitMQ çalışma mimarisi</figcaption></figure><p><strong>Producer(Publisher): </strong>Producer’lar, mesajları oluşturur, RabbitMQ sunucusuna gönderir, bir exchange methodu ile bu mesajı bir veya birden fazla kuyruğa bind eder.</p><p><strong>Consumer: </strong>Consumer, bir kuyruğa publish edilen mesajları okuyan yapıdır. Broker adresleri üzerinden rabbitmq’ya bağlanır, ve bir topic’teki mesajları dinlemeye başlar.</p><p><strong>Exchange: </strong>Exchange, mesajların alıcılara yönlendirilme şeklini ve kurallarını belirleyen bileşendir. Exchange, mesajların nereye gönderileceğini, hangi kuyruklara veya alıcılara iletilmesi gerektiğini tanımlar. Direct,Fanout,Topic,Headers gibi çeşitleri vardır.</p><p><strong>Queue: </strong>Queue, mesajların geçici olarak depolandığı ve bir consumer tarafından alınmak üzere bekletildiği bir veri yapısıdır.</p><p><strong>Binding: </strong>Binding, bir exchange ile queue(kuyruk) arasında bir ilişkiyi ifade eder. Binding, bir exchange’in hangi kuyruklara veya alıcılara mesajları ileteceğini belirler. Yani, bir kuyruk ve bir exchange arasındaki bağlantıyı tanımlar.</p><p><strong>Routing Key:</strong> Routing key, bir mesajın hangi kuyruğa yönlendirileceğini belirlemek için kullanılan bir etikettir. Routing key, mesajın nasıl yönlendirileceğini tanımlayan bir metin veya veri parçasıdır. Bir exchange (değişim) tarafından kullanılır ve bu etiket sayesinde mesajlar, belirli kuyruklara veya alıcılara iletilir.</p><p><strong>SPRING IMPLEMENTASYON</strong></p><p>Şimdi ise teorikte öğrendiğimiz bu terimlerin uygulama yaptığımızdaki karşılıklarını görelim.</p><p>1- RabbitMQ Docker Container Oluşturulması</p><pre>docker pull rabbitmq:3.10.5-management</pre><p>CMD ekranına gireceğiniz bu komut rabbitmq imajını bilgisayarımıza indirmeyi sağlar ve bu sayede rabbitmq konteynırları oluşturabiliriz.</p><pre>docker run -it --rm --name my-rabbitmq-container -p 5672:5672 -p 15672:15672 <br>rabbitmq:3-management</pre><p>İndirme işlemi bittiktten sonra ikinci olarak yukarıdaki komut satırını cmd’ye girin.Bu sizin docker ve local bilgisayarınızda 5672 portunda çalışan <em>my</em>-<em>rabbitmq-container</em> adlı bir rabbitmq container oluşturmanızı sağlayacaktır.Daha sonra docker desktop uygulamamızı açarak oluşturduğumuz container’ı kontrol edelim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YfzcpZYcL2SOGaeDP1uRFg.png" /></figure><p>Görüldüğü üzere rabbitmq container’imiz çalışmaktadır.</p><p>2-Springboot Projesi Oluşturulması</p><p>Şimdi ise bir spring boot projesi oluşturalım.Bunun için <a href="https://start.spring.io/">https://start.spring.io/</a> sitesini kullanacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ENngdy9px9tL0MN83Mbgpw.png" /></figure><p>Spring Web: Web uygulamalar yazmak için MVC modülünü sağlayan dependecy’dir.</p><p>Lombok: Getter, Setter, toString… gibi methodları yazmaktan kurtaran dependecy’dir.</p><p>Spring for RabbitMQ: RabbitMQ’ya bağlanmak için gerekli native kütüphanelerin ve spring’in RabbitMq entegrasyonu ile ilgili gerekli modülleri(ConnectionFactory,RabbitTemplate…) barındıran dependecy’dir.</p><p>3-Springboot ile RabbitMQ bağlanması</p><p>Oluşturduğumuz proje ile RabbitMQ’yu birbirine bağlamak için <strong><em>application.properties</em></strong> dosyasında şu değişikliklere ihtiyacımız vardır:</p><pre>spring.rabbitmq.host=localhost<br>spring.rabbitmq.port=5672<br>spring.rabbitmq.username=guest<br>spring.rabbitmq.password=guest<br><br>rabbitmq.queue.name=stringqueue<br>rabbitmq.json.queue.name=jsonqueue<br>rabbitmq.exchange.name=exchange<br>rabbitmq.routing.key=string_routing_key<br>rabbitmq.routing.key.json=json_routing_key</pre><p>Bu ayarları yaptıktan sonra RabbitMQ Panel’ine <strong>localhost://15672 </strong>üzerinden kullanıcı adı <strong>guest </strong>şifre <strong>guest </strong>olarak giriş yapabiliriz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_jiSzI2-4KWuvweqgPQADA.png" /><figcaption>RabbitMQ Panel</figcaption></figure><p>Şifre ve kullanıcı adını guest olarak giriş yaptıktan sonra RabbitMQ paneli şekilde gibi bizi karşılayacakatır.Bu paneli inceleyerek detaylı bilgi sahibi olabilirsiniz. Diğer adımımıza geçelim :)</p><p>4-Spring Boot RabitMQ Konfigürasyonu</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*7xf_nXk8khu04GfN0BFD0Q.png" /></figure><p>Daha sonra oluşturduğumuz projede bu şekilde bir paket yapısı kuralım ve “<em>config”</em> paketi içerisinde “<em>RabbitMQConfiguration”</em> class’ını oluşturalım.</p><pre>package com.example.rabbitmq.config;<br><br>import org.springframework.amqp.core.*;<br>import org.springframework.amqp.rabbit.connection.ConnectionFactory;<br>import org.springframework.amqp.rabbit.core.RabbitTemplate;<br>import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;<br>import org.springframework.amqp.support.converter.MessageConverter;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.context.annotation.Bean;<br>import org.springframework.context.annotation.Configuration;<br><br>@Configuration<br>public class RabbitMQConfig {<br><br>    @Value(&quot;${rabbitmq.queue.name}&quot;)<br>    String queue;<br><br>    @Value(&quot;${rabbitmq.exchange.name}&quot;)<br>    String exchange;<br><br>    @Value(&quot;${rabbitmq.routing.key}&quot;)<br>    String routingKey;<br><br>    @Value(&quot;${rabbitmq.routing.key.json}&quot;)<br>    String routingKeyJSON;<br><br>    @Value(&quot;${rabbitmq.json.queue.name}&quot;)<br>    String jsonQueue;<br><br>    @Bean<br>    public Queue queue(){<br>        return  new Queue(queue);<br>    }<br><br>    @Bean(&quot;${rabbitmq.json.queue.name}&quot;)<br>    public  Queue jsonQueue(){<br>        return  new Queue(jsonQueue);<br>    }<br><br>    @Bean<br>    public TopicExchange exchange(){<br>        return new TopicExchange(exchange);<br>    }<br><br>    @Bean<br>    public Binding binding(){<br>        return BindingBuilder.bind(queue())<br>                .to(exchange())<br>                .with(routingKey);<br>    }<br><br>    @Bean<br>    public Binding bindingJSON(){<br>        return BindingBuilder.bind(jsonQueue())<br>                .to(exchange())<br>                .with(routingKeyJSON);<br>    }<br><br>    @Bean<br>    public MessageConverter converter(){<br>        return new Jackson2JsonMessageConverter();<br>    }<br><br>    @Bean<br>    public AmqpTemplate amqpTemplate(ConnectionFactory connectionFactory){<br>        RabbitTemplate rabbitTemplate=new RabbitTemplate(connectionFactory);<br>        rabbitTemplate.setMessageConverter(converter());<br>        return  rabbitTemplate;<br>    }<br><br>}</pre><p>Konfigürasyonlarımızı tamamladıktan sonra artık bir Producer oluşturmaya başlayabiliriz.</p><p>5- Producer Oluşturulması</p><p>Burada birbirinden farklı işler yapan birden fazla Producer oluşturulabilir.Bu örnekte bir tane String mesaj üreten ve bir tane de JSON mesaj üreten iki farklı producer’ın oluşturulması örneği olacaktır.Bu class’lar projemizdeki “<em>publisher” </em>paketi altında oluşturulmuşturç</p><p>a)String Message Producer</p><pre>package com.example.rabbitmq.producer;<br><br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.amqp.rabbit.core.RabbitTemplate;<br>import org.springframework.beans.factory.annotation.Autowired;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Service;<br><br>@Service<br><br>public class RabbitMQProducer {<br><br>    @Value(&quot;${rabbitmq.exchange.name}&quot;)<br>    private String exchange;<br><br>    @Value(&quot;${rabbitmq.routing.key}&quot;)<br>    private String routingKey;<br><br>    private static final Logger LOGGER= LoggerFactory.getLogger(RabbitMQProducer.class);<br><br>    private RabbitTemplate rabbitTemplate;<br><br>    @Autowired<br>    public  RabbitMQProducer(RabbitTemplate rabbitTemplate){<br>        this.rabbitTemplate=rabbitTemplate;<br>    }<br><br>    public void sendMessage(String message) {<br>        LOGGER.info(String.format(&quot;Message sent -&gt; %s&quot;,message));<br>        rabbitTemplate.convertAndSend(exchange,routingKey,message);<br>    }<br>}</pre><p>b) JSON Message Producer</p><pre>package com.example.rabbitmq.producer;<br><br>import com.example.rabbitmq.dto.User;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.amqp.rabbit.core.RabbitTemplate;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class RabbitMQJsonProducer {<br><br>    @Value(&quot;${rabbitmq.exchange.name}&quot;)<br>    private String exchange;<br><br>    @Value(&quot;${rabbitmq.routing.key.json}&quot;)<br>    private String jsonRountingKey;<br><br><br>    private static  final Logger LOGGER= LoggerFactory.getLogger(RabbitMQJsonProducer.class);<br>    private RabbitTemplate rabbitTemplate;<br><br>    public  RabbitMQJsonProducer(RabbitTemplate rabbitTemplate){<br>        this.rabbitTemplate=rabbitTemplate;<br>    }<br>    public  void sendJsonMessage(User user){<br>        LOGGER.info(String.format(&quot;JSON Messasge sent-&gt; %s&quot;,user.toString()));<br>        rabbitTemplate.convertAndSend(exchange,jsonRountingKey,user);<br>    }<br><br>}</pre><p>Daha sonraki adım olarak bir RestController açarak ürettiğimiz Producer’lar ile RabbitMQ’ya mesaj gönderebiliriz.</p><p>6-RabbitMQ Mesaj Gönderilmesi</p><p>Burada oluşturduğumuz iki ayrı Producer için iki ayrı RestConroller’ı “<em>controller” </em>paketi altında oluşturalım.</p><p>a) Controller for String Message Producer</p><pre>package com.example.rabbitmq.controller;<br><br><br>import com.example.rabbitmq.producer.RabbitMQProducer;<br>import lombok.RequiredArgsConstructor;<br>import org.springframework.http.ResponseEntity;<br>import org.springframework.web.bind.annotation.GetMapping;<br>import org.springframework.web.bind.annotation.RequestMapping;<br>import org.springframework.web.bind.annotation.RequestParam;<br>import org.springframework.web.bind.annotation.RestController;<br><br>@RestController<br>@RequestMapping(&quot;/api/v1&quot;)<br>@RequiredArgsConstructor<br>public class MessageController {<br><br>    private final RabbitMQProducer rabbitMQProducer;<br><br>    @GetMapping(&quot;/publish&quot;)<br>    public ResponseEntity&lt;String&gt; sendMessage(@RequestParam(&quot;message&quot;) String message){<br>        rabbitMQProducer.sendMessage(message);<br>        return ResponseEntity.ok(&quot;Message sent to RabbitMQ...&quot;);<br>    }<br>}</pre><p>Bu rest controller ile RequestParam olarak aldığımız “<em>message” </em>parametresi içine yazdığımız mesajı “<em>RabbitMQProducer” </em>üzerinden RabbitMQ’ya yollayabiliriz.</p><p>b) Controller for JSON Message Producer</p><p>Json Controller’ımızı yazmadan önce JSON objesi olarak RabbitMQ’ya yollayacağımız “User” class’ını “dto” paketi altında oluşturalım.</p><pre>package com.example.rabbitmq.dto;<br><br>import lombok.Data;<br><br>@Data<br>public class User {<br>    private  int id;<br>    private String firstName;<br>    private String lastName;<br>}</pre><p>Daha sonra JSON Producer için RestController’ımızı oluşturalım.</p><pre>package com.example.rabbitmq.producer;<br><br>import com.example.rabbitmq.dto.User;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.amqp.rabbit.core.RabbitTemplate;<br>import org.springframework.beans.factory.annotation.Value;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class RabbitMQJsonProducer {<br><br>    @Value(&quot;${rabbitmq.exchange.name}&quot;)<br>    private String exchange;<br><br>    @Value(&quot;${rabbitmq.routing.key.json}&quot;)<br>    private String jsonRountingKey;<br><br><br>    private static  final Logger LOGGER= LoggerFactory.getLogger(RabbitMQJsonProducer.class);<br>    private RabbitTemplate rabbitTemplate;<br><br>    public  RabbitMQJsonProducer(RabbitTemplate rabbitTemplate){<br>        this.rabbitTemplate=rabbitTemplate;<br>    }<br>    public  void sendJsonMessage(User user){<br>        LOGGER.info(String.format(&quot;JSON Messasge sent-&gt; %s&quot;,user.toString()));<br>        rabbitTemplate.convertAndSend(exchange,jsonRountingKey,user);<br>    }<br><br>}</pre><p><em>“RabitTemplate” </em>üzerinden “<em>convertAndSend” </em>methodu ile JSON mesajımızı RabbitMQ’ya gönderdik ve şimdi bu mesajları Consumer’lar oluşturarak okuyabiliriz.</p><p>7- Consumer’lar Oluşturulması(Mesajların Okunması)</p><p>Aynı şekilde burada da oluşturduğumuz iki ayrı Producer için iki ayrı Consumer’ı “<em>consumer” </em>paketi altında oluşturalım.</p><p>a) Consumer for String Producer</p><pre>package com.example.rabbitmq.consumer;<br><br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.amqp.rabbit.annotation.RabbitListener;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class RabbitMQConsumer {<br><br>    private static final Logger LOGGER= LoggerFactory.getLogger(RabbitMQConsumer.class);<br><br>    @RabbitListener(queues = {&quot;${rabbitmq.queue.name}&quot;})<br>    public void consume(String message){<br>        LOGGER.info(String.format(&quot; Received message -&gt; %s&quot;,message));<br>    }<br>}</pre><p>Buradaki önemli nokta <strong>@RabbitListener</strong> anotasyonudur. Bu anotasyon içerisindeki <em>queues </em>parametresine verdiğimiz kuyruk ismine gider ve oradaki mesajları okumamızı sağlar.</p><p>b) Consumer for JSONProducer</p><pre>package com.example.rabbitmq.consumer;<br><br>import com.example.rabbitmq.dto.User;<br>import org.slf4j.Logger;<br>import org.slf4j.LoggerFactory;<br>import org.springframework.amqp.rabbit.annotation.RabbitListener;<br>import org.springframework.stereotype.Service;<br><br>@Service<br>public class RabbitMQJsonConsumer {<br><br>    private static final Logger LOGGER= LoggerFactory.getLogger(RabbitMQJsonConsumer.class);<br><br>    @RabbitListener(queues = {&quot;${rabbitmq.json.queue.name}&quot;})<br>    public  void  consumeJsonMessage(User user){<br>        LOGGER.info(String.format(&quot;Recieved JSON message -&gt; %s&quot;,user.toString()));<br>    }<br>}</pre><p>Buradaki “<em>consumeJsonMessage” </em>methodu RabbitMQ’da ilgili kuyruktan aldığı mesajı log olarak ekrana basmamızı sağlar. Bu şekilde RabbitMQ kuyruklarındaki mesajları okuyabiliriz.</p><p><strong>ÖZET</strong></p><p>Gelişen teknoloji,artan ve değişen ihtiyaçlar ile beraber hayatımıza farklı teknolojiler ve farklı proje mimarileri girmiştir. Bu mimarilerde biri de Microservis mimarisidir. Mikroservis mimarisi içerisindeki bölünmüş projelerin birbirleri arasındaki iletişim çok önemli bir paya sahiptir.RabbitMQgibi ADMQ(Advanced Message Queues) teknolojiler bu noktada çok önemli bir rol oynamaktadır. Bu teknolojiler sayesinde servisler arasındaki iletişim kurulur. Bunun yanı sıra RabbitMQ sunucular arasındaki iletişimi sağlayarak büyük ölçekli, dağıtılmış sistemlerin oluşturulmasına, işlerin sırayla işlenmesine ve önceliklendirilmesine, günlük(log) verilerini toplama ve merkezi bir konumda saklaması gibi konularda da kullanılmaktadır.</p><p>Umarım faydalı bir yazı olmuştur :)</p><p>İyi çalışmalar dilerim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eba677292a0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SOLID Yazılımın 5 Şartı !]]></title>
            <link>https://medium.com/@emir.baran255/solid-yaz%C4%B1l%C4%B1m%C4%B1n-5-%C5%9Fart%C4%B1-40cf4661e575?source=rss-82ed5684017d------2</link>
            <guid isPermaLink="false">https://medium.com/p/40cf4661e575</guid>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[liskov-substitution]]></category>
            <category><![CDATA[open-closed-principle]]></category>
            <dc:creator><![CDATA[Emirhan Baran]]></dc:creator>
            <pubDate>Wed, 19 Jul 2023 18:02:39 GMT</pubDate>
            <atom:updated>2023-07-19T18:02:39.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>SOLID Yazılımın 5 Şartı !</h3><p><strong>“Uygulama geliştirirken kodlarınızı Solid prensiplerine göre geliştirmelisiniz.</strong>” <em>Bu cümleyi belki eğitim belki de iş kariyerinizde yüzlerce kez duymuşsunuzdur veya duyacaksınızdır. Bu yazımda her yazılımcının bilmesi gereken bu prensipler nedir bunlardan bahsedeceğiz. Keyifli okumalar…</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4uyMUTTuXLIqgJHLqaptbg.png" /></figure><h3>SOLID prensipleri nedir ve neden kullanılır?</h3><p>Büyük ölçekte projeler geliştiriliyor, bu projeleri birçok kişi beraber geliştiriyor ve geliştirilen bu projeler için uzun uzun kodlar yazılabiliyor. İşte tam bu noktada Robert C. Martin’in öne sürdüğü SOLID prensipleri geliştirilen yazılımın esnek, yeniden kullanılabilir, okunulur, bakımını kolaylaştıran, kod tekrarını önlemeye yarayan kurallar bütünü olarak karşımızı çıkıyor ve işlerimizi kolaylaştırıyor. Bu prensipleri kullanarak uygulamalarımızın büyürken, karmaşıklığın da büyümesinin önüne geçmiş oluruz bu da bir yazılımcı olarak kalitenizi gösterecek en önemli özelliklerdendir.</p><p>SOLID nedir ve neden kullanıldığını sorularının cevabını öğrendik, şimdi ise bu prensiplerin neler olduğunu tek tek inceleyerek ve görsellerimizle örnekleştirerek anlayalım. (Bu konuda birçok makale kod ile örneklerde bulunuyor fakat görsellerle anlatan makale çok göremedim, görsel kullanmanın akılda kalıcılığını arttıracağını düşündüğümden görseller ile anlatacağım.)</p><p>Haydi Başlayalım!</p><h3>SOLID Prensipleri</h3><p><strong>S — Single Responsibility (Tek Sorumluluk Prensibi)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O6P1efVywJovPbsDZynD-A.png" /></figure><p>Bir sınıfın(class) bir methodun(fonksiyon) veya bir paket(modül) yapısına birden çok göreve sahip olması buralarda oluşabilecek hataları arttırır çünkü eğer bir sınıf, method ya da paket yapısının birden fazla görev alması durumunda bir görevde yapaılacak olan değişiklikler sonunda diğer görevler de bundan etkilenerek hata alabilir. Bu prensibin ise bize der ki <strong>“Her sınıfın, fonksiyonun veya paketin yalnızca bir sorumluluğu olmalıdır.”</strong></p><p><strong>O — Open-Closed (Açık/Kapalı Prensibi)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNSD-lPPob8C49dBuiaA4A.png" /></figure><p>Bu presibe uygun yazmadığımız kodlarda ilk fotoğrafta görüldüğü gibi bir sınıf(class)’ta değişim yapmak o sınıfın davranışlarını tümüyle etkileyecektir.(Robotumuz ilk başta kesim yapan bir robot iken yapılan değişiklik sonucu kesim yapma özelliği alınıp boyama özelliği gelmiştir.) Fakat bu prensibe uygun yazar isek robotumuz iki özelliğe birden sahip olacaktır. Yani bu prensibin ise bize der ki “ <strong>Sistem davranışları değişebilir, ancak mevcut kod değiştirilmeden yeni işlevselliği eklemek mümkün olmalıdır. Yani, kod değiştirmeden, sadece yeni kod ekleyerek genişletilebilir olmalıdır.</strong>”</p><p><strong>L </strong>— <strong>Liskov Substitution (Liskov Yerine Geçme Prensibi)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Bv5xFfreNw0Nosw5G4kfQ.png" /></figure><p>Bu örneğimizde bir robotumuz ve onun çocuğu vardır. Bunları bir sınıf ve onu extend alan bir diğer sınıfa benzetebiliriz. Burada ana sınıfımız (parent class) kahve yapabiliyorken ondan miras alan çocuk sınıfımızın(child class) kahve yapabilme gibi bir özelliği yoktur böyle bir miras kullanımı yanlış bir kullanımdır. Bu prensip bize der ki “<strong>Alt sınıflar üst sınıfların taşıdığı değişkenleri veya methodları tamamını kullanabilmelidir ve alt sınıflar, üst sınıfların yerine geçebilmelidir.</strong> ”</p><p><strong>I </strong>— <strong>Interface Segregation(Arayüz Ayrım Prensibi)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K6EM0MzupAi4JGbl8HMmyA.png" /></figure><p>Bu örneğimizde ise robotların yapabildiği hareketler bir tabloya yazılmaktadır. İlk tabloda görüldüğü gibi bir robottan spin around, rotatic arms, wiggle anternas gibi tüm hareketleri yababildiği varsayılmıştır bu tablooyu bir interface gibi ve oradaki olan hareketleri o interface’in içine yazılmış methodlar gibi düşünürsek bunu implement eden robotlar tüm bu özellikleri taşımak fakat tüm bu özellikleri aynı anda taşıması zordur bu yüzden ikinci tabloda elimizdeki tabloyu üç ayrı parçaya bölmemiz bize daha esnek bir yapı getirecektir. Bu sayede elimizde olan üç tane tablodan hangisi veya hangileri uygun ise bunları kullanarak daha doğru bir yapıya ulaşırız. Bu prensip ise tıpkı bu örnekteki gibidir ve bize şunu der: “<strong>Methodların hepsini tek bir arayüze toplamak yerine daha özelleştirilmiş birden fazla arayüz oluşturmak gerekir.</strong>”</p><p><strong>D </strong>— <strong>Dependency Inversion(Bağımlılığı Tersine Çevirme Prensibi)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6IWpB6JTLMJnXsymbY_Vcw.png" /></figure><p>Bu prensip ise der ki: “<strong>Bağımlılıklar, soyutlamalara dayanmalıdır. Yüksek seviyeli sınıflar, düşük seviyeli sınıflara doğrudan bağlı olmamalıdır. Bunun yerine, soyutlamalar (arayüzler veya soyut sınıflar ) kullanarak bağımlılıklar tersine çevrilmelidir. Bu, bağımlılıkların değiştirilebilir ve esnek olmasını sağlar.</strong>”</p><p><strong>Özet</strong></p><p>Bu prensipler yazılımın daha iyi tasarlanması ve bakımını kolaylaştıran temel ilkelerdir. Biz kod geliştiricileri yazılım tasarımı ve geliştirmesi sürecinde bu prensiplere uyarak, kaliteli, esnek ve sürdürülebilir yazılımlar oluşturmalıyız.</p><p>Bana Ulaşmak İçin:</p><ul><li>Linkedin: <a href="https://linkedin.com/in/emirhanbaran0">https://linkedin.com/in/emirhanbaran0</a></li><li>Github: <a href="https://github.com/emirhanbaran0">https://github.com/emirhanbaran0</a></li></ul><h3>REFERANSLAR</h3><ul><li><a href="https://medium.com/backticks-tildes/the-s-o-l-i-d-principles-in-pictures-b34ce2f1e898">The S.O.L.I.D Principles in Pictures</a> by Ugonna Thelma</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40cf4661e575" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java ile Factory Design Pattern’i Anlamak]]></title>
            <link>https://medium.com/@emir.baran255/java-ile-factory-design-patterni-anlamak-bad770e791b6?source=rss-82ed5684017d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bad770e791b6</guid>
            <category><![CDATA[tasarım-desenleri]]></category>
            <category><![CDATA[factory-pattern]]></category>
            <category><![CDATA[factory-design-pattern]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[design-pattern-in-java]]></category>
            <dc:creator><![CDATA[Emirhan Baran]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 07:31:05 GMT</pubDate>
            <atom:updated>2023-07-04T07:31:05.810Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Merhabalar, bu yazımda Factory design pattern nedir? Hangi durumlarda ve nasıl kullanmalıyız sorularının cevaplarını konuşacağız. Factory Design Pattern için yapacağımız java uygulaması ile factory design pattern’in neden kullanıldığını inceleyeceğiz. Keyifli okumalar…</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZBHWYmbuN2bO2Z2Vc1Azsw.jpeg" /></figure><p>Bu, tasarım deseni makale serisinin ikinci makalesidir. Henüz önceki makaleleri okumadıysanız, bu makaleye geçmeden önce onu okumanızı öneririm.</p><p><strong>Makale serisi:</strong> <a href="https://medium.com/@emir.baran255/list/design-patternlar-anlamak-794bf2b7acd9"><em>Design Pattern’ları Anlamak</em></a></p><p><strong><em>Factory Design Pattern Neden Kullanılır?</em></strong></p><p>Design Pattern’lar yazılımcıların ortak olarak karşılaştığı probleme ortak olarak bulunan çözüm yöntemleridir. Her design pattern bir durumu çözmek yada kolaylaştırmak için kullanılır. Asıl sorumuza dönecek olursak Factory design pattern ise nesne yaratma işlemini daha esnek, genişletilebilir ve sürdürülebilir hale getirmek için kullandığımız <strong>creational tasarımsal desenlerden</strong> biridir. Aşağıda Factory Design Pattern’in bize sağladığı 3 temel kolaylığı göreceğiz.</p><p><strong><em>Factory Design Pattern’in Sağladığı Kolaylıklar Nelerdir?</em></strong></p><ol><li>Factory design pattern, <strong>client(istemci)</strong> kodunun somut nesne yaratma işleminden bağımsız olmasını sağlar. C<strong>lient</strong>, sadece bir fabrika sınıfı üzerinden nesne yaratma talebi gönderir ve geri dönen nesneyi kullanır. Bu sayede, istemcinin nasıl oluşturulduğunu bilmesi gerekmez ve daha <strong>esnek</strong> bir yapı oluşur.</li><li>Nesne oluşturma sürecini tek bir sınıf(Fabrika Sınıfı )üzerinden <strong>nesne oluşturma sürecini merkezileştirir</strong>. Bu, nesnelerin nasıl oluşturulduğuna dair kodun tek bir yerde yönetilmesini sağlar. Böylece, nesne oluşturma kodunu değiştirmek veya güncellemek gerektiğinde, sadece fabrika sınıfı üzerinde yapılan değişiklikler yeterli olur, bu da bize <strong>SOLID prensiplerinden</strong> <strong>Open-Closed prensipini</strong> destekleyen bir yapı kurmamızı sağlar.</li><li>Nesne yaratmayı genişletilebilir hale getirir. Yeni bir nesne yaratmak istendiğinde, yalnızca fabrika sınıfına yeni bir metot eklenir ve istemci kodunda herhangi bir değişiklik yapılmasına gerek kalmaz. Bu, sistemde yeni özellikler eklemeyi ve mevcut özellikleri değiştirmeyi kolaylaştırır. Ayrıca, ilgili sınıflar arasındaki bağımlılığı azaltır, böylece bir sınıfta yapılan değişikliklerin diğer sınıflara minimum etkisi olur.</li></ol><p><strong><em>Factory Design Pattern Gerçek Hayat Örneği</em></strong></p><p>Haydi şimdi bunları daha iyi anlamak için bir örnek yapalım. Bu örneğimizde bir zeytin fabrikası düşünelim ve bu zeytin fabrikasının 3 farklı zeytin türü(yeşil zeytin, siyah zeytin, sarı zeytin) üretiyor ve bu üretimlerin hepsi Zeytin Fabrikasından gerçekleşiyor bu sayede merkezi bir yapı kuruluyor ve yeni bir zeytin modeli eklenmek istediğinde sadece fabrikaya giderek bu zeytin modelini ekleyebiliyoruz ve esnekliği, sürdürülebilirliği sağlıyoruz.</p><pre>public interface Zeytin {<br>    public void zeytinOluşturma();<br>}</pre><p>Öncelikle tüm zeytinlerimiz ortak olarak oluşturulma özelliğine sahip olacağından bunları bir interface ile kullanalarak ortak bir yapı kuracağız.</p><pre>public class SariZeytin implements Zeytin {<br>    @Override<br>    public void zeytinOluşturma() {<br>        System.out.println(&quot;Sari zeytin işleniyor.&quot;);<br>    }<br>}<br><br>public class SiyahZeytin implements Zeytin {<br>    @Override<br>    public void zeytinOluşturma() {<br>        System.out.println(&quot;Siyah zeytin işleniyor.&quot;);<br>    }<br>}<br><br>public class YesilZeytin implements Zeytin {<br>    @Override<br>    public void zeytinOluşturma() {<br>        System.out.println(&quot;Yeşil zeytin işleniyor.&quot;);<br>    }<br>}</pre><p>Zeytin sınıfını implement eden zeytin sınıflarımız burada oluşmaktadırlar.</p><pre>public class ZeytinFabrikası {<br><br>    public Zeytin createOlive(String zeytinTuru){<br>        switch (zeytinTuru){<br>            case &quot;Yeşil Zeytin&quot;:<br>                return  new YesilZeytin();<br>            case &quot;Siyah Zeytin&quot;:<br>                return new SiyahZeytin();<br>            case &quot;Sarı Zeytin&quot;:<br>                return new SariZeytin();<br>            default:<br>                return new SiyahZeytin();<br>        }<br>    }<br>}</pre><p>Zeytin Fabrikamız ise burada oluşmaktadır.</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        // Fabrika sınıfı kullanarak zeytini oluştur<br>        ZeytinFabrikası fabrika = new ZeytinFabrikası();<br>        Zeytin zeytin1 = fabrika.createOlive(&quot;Yeşil&quot;);<br>        Zeytin zeytin2 = fabrika.createOlive(&quot;Siyah&quot;);<br><br>        // Zeytinleri işle<br>        zeytin1.zeytinOluşturma();<br>        zeytin2.zeytinOluşturma();<br>    }<br>}</pre><p>Bir zeytin oluşturmak artık bu kadar kolay :) Bu örnek, Factory tasarım desenini basit bir şekilde göstermektedir. İstemci, somut ürünün nasıl oluşturulduğu hakkında bilgi sahibi olmadan ürünü kullanabilir. Ayrıca, yeni bir ürün eklemek istendiğinde yalnızca fabrika sınıfına bir metot eklemek yeterlidir.</p><p>Fakat çok fazla zeytin çeşidi olduğu durumda çok fazla koşul durumu içerebilir. Bu durum, tasarlanan metodu if/else if/else<strong> </strong>yapıları ile doldurabilektedir. Ayrıca her eklenilen zeytin sınıfı için bu metotta değişikliğe gidilmeli, yeni kod satırları eklenmelidir. Bu durum Clean Code açısından uygun değildir. Peki ne yapmalıyız? Bu sorunun cevabı için <strong>Abstract Factory Pattern’i </strong>araştırabilirsiniz.</p><p>İyi çalışmalar dilerim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bad770e791b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Java ile Builder Design Pattern’i Anlamak]]></title>
            <link>https://medium.com/@emir.baran255/java-ile-builder-design-patterni-anlamak-12126f46e1b6?source=rss-82ed5684017d------2</link>
            <guid isPermaLink="false">https://medium.com/p/12126f46e1b6</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[builder-design-pattern]]></category>
            <category><![CDATA[tasarım-desenleri]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Emirhan Baran]]></dc:creator>
            <pubDate>Sun, 25 Jun 2023 17:15:08 GMT</pubDate>
            <atom:updated>2023-07-03T19:48:25.443Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Merhabalar, bu yazımda Builder design pattern nedir? Hangi probleme çözüm olarak kullanılır? sorularına cevap arayacağız ve verilecek olan bir örneğe kötüden iyiye doğru üç çözüm yolu göstereceğim bu şekkilde Builder Design Pattern’in neden kullanıldığını daha net bir şekilde gözlemleyebileceksiniz. Keyifli okumalar…</em></p><figure><img alt="builder design patter, builder tasarım düzeni" src="https://cdn-images-1.medium.com/max/310/1*Qr0n0yYI-YHKNkpWsJm0JQ.png" /></figure><p>Bu, tasarım deseni makale serisinin ilk makalesidir. Henüz önceki makaleleri okumadıysanız, bu makaleye geçmeden önce onu okumanızı öneririm.</p><p><strong>Makale serisi:</strong> <a href="https://medium.com/@emir.baran255/list/design-patternlar-anlamak-794bf2b7acd9"><em>Design Pattern’ları Anlamak</em></a></p><p><strong><em>Builder Design Pattern nedir ve hangi probleme çözüm olmuştur ?</em></strong></p><p>Bildiğiniz gibi Java Nesne Tabanlı bir programlama dilidir ve biz de nesneleri oluşturmak için <strong>constructor </strong>adlı özel bir methoda ihtiyaç duyarız. Bu nesneler ise oluşurken bazı zorunlu ve opsiyonel parametrelere ihtiyaç duyabilir bu nedenle ihtiyaç duyacakları alan sayısı oluşacak nesnenin özelinde değişkenlik gösterebilir. Statik olarak oluşturacağımız constructor methodları bize burada çok iyi bir çözüm getirmeyecektir işte bu gibi durumlarda Builder Design kullanarak bu problemi aşabiliriz. Aşağıdaki fotoğraf ile önce problemi görsel olarak ele alıp daha bunu bir java koduna dökerek nasıl kullanıldığını anlayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WoC3znewKNGPEom_nnvk4Q.png" /></figure><p>Yukarıdaki fotoğrafta <strong><em>house </em></strong>oluşacak olan nesne gibi düşünürsek. Bir house için oda sayısı, genişliği, yüksekliği, pencere sayısı, kapı sayısı gibi olmazsa olmaz özellikler vardır birde bunlara ek olarak bir ev garaj, havuz bahçe gibi ek özelliklere sahip olabilir.Peki böyle bir durum için nasıl bir yol izlemeliyiz? Şimdi sizlere kötüden iyiye olarak sıraladığım 3 çözümü kod üstünde göstereceğim.</p><pre>package BuilderDesignPattern;<br><br>public class Bahce {<br>    int agacSayisi;<br>}<br><br>public class Garaj{<br>  int yukseklik,genislik;<br>}<br><br>public class Havuz{<br>  dounble hacim;<br>}</pre><p>Yukarıda evin sahip olabileceği özelliklerden olan Bahçe, Garaj ve Havuz sınıfı oluşturulmuştur. Bu sınıflara daha fazla özellik verilebilir fakat asıl önemli nokta burası olmadığı için bu kadar yeterlidir. Şimdi evi temsil edecek House sınıfını oluşturalım.</p><pre><br><br>public class House {<br><br>    //Kesinlikle olması gereken özellikler<br>    int odaSayisi,pencereSayisi,kapiSayisi;<br>    double genislik,yukseklik;<br><br>    //İsteğe bağlı özellikler<br><br>    Garaj garaj;<br>    Havuz havuz;<br>    Bahce bahce;<br><br>    public House(int odaSayisi, int pencereSayisi, int kapiSayisi, double genislik, double yukseklik) {<br>        this.odaSayisi = odaSayisi;<br>        this.pencereSayisi = pencereSayisi;<br>        this.kapiSayisi = kapiSayisi;<br>        this.genislik = genislik;<br>        this.yukseklik = yukseklik;<br>    }<br><br>    public House(int odaSayisi, int pencereSayisi, int kapiSayisi, double genislik, double yukseklik, Garaj garaj) {<br>        this.odaSayisi = odaSayisi;<br>        this.pencereSayisi = pencereSayisi;<br>        this.kapiSayisi = kapiSayisi;<br>        this.genislik = genislik;<br>        this.yukseklik = yukseklik;<br>        this.garaj = garaj;<br>    }<br><br>    public House(int odaSayisi, int pencereSayisi, int kapiSayisi, double genislik, double yukseklik, Garaj garaj, Havuz havuz) {<br>        this.odaSayisi = odaSayisi;<br>        this.pencereSayisi = pencereSayisi;<br>        this.kapiSayisi = kapiSayisi;<br>        this.genislik = genislik;<br>        this.yukseklik = yukseklik;<br>        this.garaj = garaj;<br>        this.havuz = havuz;<br>    }<br><br>    public House(int odaSayisi, int pencereSayisi, int kapiSayisi, double genislik, double yukseklik, Bahce bahce) {<br>        this.odaSayisi = odaSayisi;<br>        this.pencereSayisi = pencereSayisi;<br>        this.kapiSayisi = kapiSayisi;<br>        this.genislik = genislik;<br>        this.yukseklik = yukseklik;<br>        this.bahce = bahce;<br>    }<br>}</pre><p>Yukarıda görüldüğü gibi House sınıfı kesinlikle olması gerek ve isteğe bağlı olan özelliklere sahiptir ve burada alabileceği özellik sayısı 8&#39;dir.(Başka örneklerde bu özellik sayısı daha da artabilir). Peki bir ev nesnesi üretmek istediğimizde nasıl bir yol izlemeliyiz. Yukarıdaki gibi farklı farklı contructor methodları oluşturarak ihtiyacımıza göre bunları kullanabiliriz fakat göreceğiniz gibi değişken sayımız çok az sayıda iken bile birçok contructor methodu oluşturmamız gerekecektir ve bu performanslı iyi bir çözüm değildir.Haydi şimdi Builder Design Pattern’in bu sorunu nasıl çözdüğünü görelim.</p><pre><br><br>public class House {<br><br>    //Kesinlikle olması gereken özellikler<br>    int odaSayisi,pencereSayisi,kapiSayisi;<br>    double genislik,yukseklik;<br><br>    //İsteğe bağlı özellikler<br><br>    Garaj garaj;<br>    Havuz havuz;<br>    Bahce bahce;<br><br>    House(Builder builder){<br><br>            odaSayisi=builder.odaSayisi;<br>            pencereSayisi=builder.pencereSayisi;<br>            kapiSayisi=builder.pencereSayisi;<br>            genislik=builder.genislik;<br>            yukseklik=builder.yukseklik;<br>            garaj= builder.garaj;<br>            havuz= builder.havuz;<br>            bahce= builder.bahce;<br>    }<br><br><br>     public static class Builder{<br>         int odaSayisi,pencereSayisi,kapiSayisi;<br>         double genislik,yukseklik;<br>         Garaj garaj;<br>         Havuz havuz;<br>         Bahce bahce;<br><br>         public Builder odaSayisi(int odaSayisi) {<br>             this.odaSayisi = odaSayisi;<br>             return this;<br>         }<br><br>         public Builder pencereSayisi(int pencereSayisi) {<br>             this.pencereSayisi = pencereSayisi;<br>             return this;<br>         }<br><br>         public Builder kapiSayisi(int kapiSayisi) {<br>             this.kapiSayisi = kapiSayisi;<br>             return this;<br>         }<br><br>         public Builder genislik(double genislik) {<br>             this.genislik = genislik;<br>             return this;<br>         }<br><br>         public Builder yukseklik(double yukseklik) {<br>             this.yukseklik = yukseklik;<br>             return this;<br>         }<br><br>         public Builder createGaraj(Garaj garaj) {<br>             this.garaj = garaj;<br>             return this;<br>         }<br><br>         public Builder createHavuz(Havuz havuz) {<br>             this.havuz = havuz;<br>             return this;<br>         }<br><br>         public Builder createBahce(Bahce bahce) {<br>             this.bahce = bahce;<br>             return this;<br>         }<br><br>         public House build(){<br>             return new House(this);<br>         }<br><br>     }<br>}</pre><p>Burada kodumuzda ise çok fazla özelliğe veya isteğe bağlı özelliklere sahip olduğumuzda statik değilde dinamik bir constructor methodu oluşturmak istiyorsak Builder Design Pattern’in bize sağladığı kolaylığı görebiliriz.Aslında nesnemiz içeride bulunan B<strong><em>uilder </em></strong>adlı sınıf ile içeride istedikleri özellikleri aldıktan sonra <strong><em>build </em></strong>methodu ile anonim bir <strong><em>house </em></strong>nesnesi oluşturuluyor ve bu oluşturulan anonim nesnenin özellikleri aslında oluşturulmak istenen <strong><em>house </em></strong>nesnesine eşitleiyor.</p><pre>Garaj garaj=new Garaj();  //Eğer garaj eklenmek isterse bir garaj nesnesine ihtiç olduğu için oluşturulmuştur.<br>House house=new House.Builder().pencereSayisi(3).kapiSayisi(2).odaSayisi(4).createGaraj(garaj).build();</pre><p>Nesnemizi istediğimiz alanlar ile oluşturmak artık bu kadar kolay. Özetle Builder tasarım deseni, nesnelerin oluşturulmasını daha esnek ve kolay hale getirirken, okunabilirlik ve sürdürülebilirlik sağlar. Ayrıca, zorunlu olmayan parametreleri belirlemeyi kolaylaştırır ve nesne oluşturma sürecini daha modüler hale getirir fakat bu da görüldüğü gibi kod tekrarına sebep olabilimektedir. Sonuç olarak, tasarım desenleri güçlü araçlardır, ancak her durumda en iyi çözüm olmayabilirler. İhtiyaçlarınıza ve projenize uygun olanı seçmek ve gerektiğinde uyarlamak önemlidir.</p><p>İyi çalışmalar dilerim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12126f46e1b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>