<?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 Niyazi Ekinci on Medium]]></title>
        <description><![CDATA[Stories by Niyazi Ekinci on Medium]]></description>
        <link>https://medium.com/@niyaziekinci?source=rss-5f121ac2a598------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YXxTajzpZmkZShCDYNBjow.jpeg</url>
            <title>Stories by Niyazi Ekinci on Medium</title>
            <link>https://medium.com/@niyaziekinci?source=rss-5f121ac2a598------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 11:45:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@niyaziekinci/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[Implementing Exception Mechanism in a Toy Language]]></title>
            <link>https://niyaziekinci.medium.com/error-handling-mechanism-insights-from-my-programming-language-342b9e7406a6?source=rss-5f121ac2a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/342b9e7406a6</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[compilers]]></category>
            <dc:creator><![CDATA[Niyazi Ekinci]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 09:19:34 GMT</pubDate>
            <atom:updated>2025-03-18T23:33:06.324Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone,</p><p>Today, I would like to present the error handling mechanism of my toy programming language, sea(C). Although English is not my firxst language, I believe in sharing my work authentically — with all its imperfections — to preserve the true amateur spirit of early programming. This project reflects those early days of exploration and learning, where the joy of coding was more important than adhering to strict coding standards.</p><p>First of all, although this language is an aimed toy programming language. This was thrilled project like early programming years when we are coding in C while learning programming in university course. Amateur spirit without the worrying about clean code and best practices, which makes possible the <strong>best</strong> part of the process enjoying programming again rather than fixing Sonarlint and Fortify issues. Actually they are good as well but this is different.</p><p>So If I get to the point,</p><p>At first, we can talk about error handling types through reviewing their popular implementations on primary languages.</p><p><strong>1 — Exceptions: Throwing and Catching</strong></p><p>Java and C# are the most known languages for this kind of exceptions. When you want to handle exceptions in your method you either throw checked or unchecked exception and then you handle it through try-catch blocks.</p><p>Java code to clarify this kind of exceptions:</p><pre>private bool someMethodThrowsException(List&lt;Character&gt; args) {<br>    if (args == null || args.size() == 0) {<br>      throw new IllegalArgumentException(&quot;You must provide at least one argument&quot;)<br>    }<br><br>    return args.get(0) == &#39;Y&#39;<br>  <br>}</pre><pre>public void anotherMethodCallsMethod(){<br>    try {<br>      System.out.printf(&quot;Response: %b&quot;, someMethodThrowsException())<br>    } catch (IllegalArgumentException e) {<br>      System.out.println(e.getMessage())     <br>    } <br><br>}</pre><p><strong>2 — Error Values</strong></p><p>Golang and C are the most known languages for this kind of error handling. When you want to handle your function’s exceptional cases you must return a value that indicates the response is error indeed. The following example functions are examples.</p><pre>#define NEG_INPUT_ERROR -1<br>#define INVALID_DIVISOR_ERROR -2<br>#define SUCCESS 0<br><br>// one way to implement function<br>int positive_number_divide_1(int a, int b) {<br>    if (a &lt; 0 || b &lt; 0) {<br>      return NEG_INPUT_ERROR;<br>    }<br><br>    if (b == 0) {<br>      return INVALID_DIVISOR_ERROR;<br>    }<br><br>    return a / b;<br>   <br>}<br><br>// another way<br>int positive_number_divide_2(int a, int b, int* result) {<br>  if (a &lt; 0 || b &lt; 0) {<br>    return NEG_INPUT_ERROR;<br>  }<br><br>  if (b == 0) {<br>    return INVALID_DIVISOR_ERROR;<br>  }<br><br>  *result = a/b;<br>  return SUCCESS;<br>}<br><br>typedef struct {<br>  int error_code;<br>  int result;<br>} Result;<br><br>// yet another way<br>Result positive_number_divide_3(int a, int b) {<br>  <br>  <br>  if (a &lt; 0 || b &lt; 0) {<br>    return (Result) {.error_code = NEG_INPUT_ERROR }<br>  }<br><br>  if (b == 0) {<br>    return (Result) {.error_code = INVALID_DIVISOR_ERROR }<br>  }<br>  <br>  return (Result) {.error_code = SUCCESS, .result = a / b }<br>}<br><br>int main(int argc, char *argv[]) {<br>   int division = positive_number_divide_1(3, 0);<br>   // or call other methods here<br>   if (division == INVALID_DIVISOR_ERROR) {<br>      printf(&quot;The divisor was 0 which is invalid one.&quot;);<br>      exit(1);<br>   }<br>   <br>   if (division == NEG_INPUT_ERROR) {<br>      printf(&quot;The inputs are invalid.&quot;);<br>      exit(1);<br>   }<br><br>   printf(&quot;Result: %d\n&quot;, division);<br>} </pre><p>Or like in Golang you can return multiple valued in functions. One of them can be <strong>error </strong>type which is built-in. Let us examine.</p><pre>func divide_positive(a, b int) (int, error) {<br>  if a &lt; 0 || b &lt; 0 {<br>    return 0, fmt.Errorf(&quot;Invalid input&quot;)<br>  }<br><br>  if b == 0 {<br>    return 0, fmt.Errorf(&quot;The divisor was 0 which is invalid one.&quot;)<br>  }<br><br>  return a / b, nil<br>}<br><br>func main() {<br>  result, err := divide_positive(3, 0)<br><br>  if err != nil {<br>    panic(err.Error())<br>  }<br><br>  fmt.Printf(&quot;Result: %d\n&quot;, result)<br>}</pre><p><strong>3 —Error Handling with Result&lt;T, E&gt; and pattern matching</strong></p><p>Haskell and Rust are the most known languages for checked error handling scenarios. This is actually part of Error Values indeed but I wanted to separate. When you define a function with Result type and use this function you must explicitly handle error scenarios with pattern matching.</p><p>Let us examine.</p><pre>fn divide(a: i32, b: i32) -&gt; Result&lt;i32, String&gt; {<br>  if a &lt; 0 || b &lt; 0 {<br>    Err(String::from(&quot;Inputs are negative&quot;))<br>  }<br><br>  if b == 0 {<br>    Err(String::from(&quot;Divisor is 0&quot;))<br>  }<br><br>  Ok(a/b)<br>}<br><br>fn main() {<br>  let result = divide(3, 0)<br>  match result {<br>    Ok(value) =&gt; println!(&quot;Result: {}&quot;, value),<br>    Err(err) =&gt; println!(&quot;Error: {}&quot;, err)<br>  }<br>}</pre><p>These are basically ways to handle checked or in other words coverable errors. All are just a option with their pros and cons. Language designers/masters or companies choose a way for a reason for their languages. For example, try catch blocks may bring performance penalties or returning errors as a value may bring unmaintainable codebase for programmers.</p><h4>What is our method and why?</h4><p>I follow try-catch blocks for my own programming language.</p><p><strong>1 — Familiarity:</strong> I am more comfortable and familiar with try-catch blocks having experienced in Java.</p><p><strong>2 — Code Readability:</strong> I think this way more readable and maintainable therefore this helps improve keep codebase clean for programmers compared to manual checks. Though it may decreases the compiled program’s performance. But it is just toy language and even Java uses that way.</p><p><strong>3 — Simplicity for a toy language:</strong> Even if Rust or Haskell’s Pattern Matching way attracts me, this requires strictly pattern matching and compiler implementations. For my project, this trade-off wasn’t practical while working a full-time job.</p><p>Though handling errors through manual/error values is more simple, I have been preferring try-catch blocks.</p><pre>fun void throwsError() {<br>  println(&quot;some operation&quot;)<br>  throw &amp;error{message: &quot;error_message&quot;, error_code: 255}<br>}<br><br>fun i32 main() {<br>  try {<br>    println(&quot;beginning operations&quot;)<br>    throwsError()<br>  } catch(error* err) {<br>    println(&quot;caught error: &quot; + err.message + &quot;, code: &quot; + to_string(err.error_code))<br>  }<br>  <br>  println(&quot;continuing the process&quot;)<br>}</pre><p>This was from <a href="https://github.com/nekinci/sea">sea’s</a> syntax. This is more like C++ or Java. <strong>error</strong> type is built-in and when you want to throw an exception you primitively throw that error type in my toy language.</p><p>Let’s go into the details,</p><p>Well actually it is more like a technique.</p><p>The technique is that setjmp/longjmp functions which is the most known way from C developers. The idea is when you call the setjmp you save the current context of CPU. Stack Pointer, Program Counter or some registers are saved to be used through longjmp. When you call the longjmp with already saved context you can restore your context and jump your condition. That example may be correct us.</p><pre>#include &lt;setjmp.h&gt; <br><br>jmp_buf env;<br><br>void foo() {<br>    printf(&quot;foo called\n&quot;);<br>    longjmp(env, 3);<br>    printf(&quot;foo unreachable\n&quot;);<br>}<br><br>int main() {<br>    // save current environment to env<br>    int val;<br>    val = setjmp(env);<br>    if (val != 0) {<br>        printf(&quot;Handling error for val: %d&quot;, val);<br>        return -1;<br>    }<br>    printf(&quot;Prints something...\n&quot;);<br>    foo();<br>    printf(&quot;main unreachable\n&quot;);<br>}<br><br>// Output should be like this:<br>// Prints something...<br>// foo called<br>// Handling error for val: 3<br>// Exit code: -1</pre><p>As you can see, foo called and inside of foo function get jumped to env where is saved from main function. The val variable is assigned by longjmp’s second parameter. So val variable is 3 in this example. By this way we can handle error scenarios.</p><h4>Nested Try-Catch Blocks</h4><p>So How do you implement try-catch blocks when you have multiple try-catch statements.</p><p>Let’s clarify this.</p><p>For example you have codebases like these:</p><pre>fun i32 main() {<br>    <br>    try {<br>        try {<br>          throw &amp;error{message: &quot;inner try-catch error&quot;, error_code: 254}<br>        } catch(error* e) {<br>           println(&quot;Inner catch block: &quot; + e.message)<br>           throw &amp;error{message: e.message + &quot; (throwed again)&quot;, error_code: 255}<br>        }<br>    } catch(error* e) {<br>      if e.error_code == 255 {<br>        println(&quot;Outside catch block: &quot;e.message)<br>      }<br>    }<br>}<br><br>// The output must be like this:<br>// Inner catch block: inner try-catch error<br>// Outside catch block: inner try-catch error (rehrowed)</pre><p>The idea is simple last thrown exception must be caught last catch block. Like in the following image, we can think try catch blocks as stack when you add new try catch block you implicitly push a new error handler to stack. So If an error occurred at innermost try block then the innermost catch block would be ran.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6nsmIlChcPowxu7ZCJDgg.png" /><figcaption>Error Stack</figcaption></figure><p>According to the implementation details.</p><p>There are basically 4 global variables in our runtime program. <em>ENV_STACK</em>, <em>EXCEPTION_TABLE</em>, <em>ENV_INDEX</em> and <em>ERROR_INDEX</em>. If the compiler met try statement while compiling program then injects some code block to initialize a new jmp_buf environment and increase <em>ENV_INDEX</em> and vice versa.</p><pre>try {<br>   println(&quot;Hello world&quot;)<br>   throw &amp;error{message: &quot;foo bar&quot;, error_code: 255}<br> <br>} catch(error* e) {<br>  // handle errors<br>  println(e.message)<br>}<br><br>// this block corresponds to following code indeed, <br>// you can ignore syntactic differences<br><br>ENV_INDEX = 0<br>ERROR_INDEX = 0<br>ENV_STACK = []<br>EXCEPTION_TABLE = []<br><br>env = push_env()<br>val = set_jmp(*env)<br>if (val != 0) {<br>  pop_env()<br>  error* e = pop_exception_instance()<br>  printf(&quot;%s\n&quot;, e.message)<br>  return -1<br>}<br><br>printf(&quot;Hello world\n&quot;)<br>push_exception_instance(&quot;foo bar&quot;, 255)<br>long_jmp(pop_env(), 1)<br><br><br>//<br>void push_error_instance(char* message, int code) {<br>  error* err = malloc(sizeof(error));<br>  err.message = message;<br>  err.error_code = code;<br>  EXCEPTION_TABLE[ERROR_INDEX++] = err<br>}<br><br>error* pop_exception_instance() {<br>  error* err = EXCEPTION_TABLE[ERROR_INDEX-1]<br>  ERROR_INDEX -= 1<br>  return err<br>}<br><br>//<br>jmp_buf* push_env() {<br>  jmp_buf* env = malloc(sizeof(jmp_buf));<br>  ENV_STACK[ENV_INDEX] = env<br>  ENV_INDEX += 1<br>  return env<br>}<br></pre><p>Consequently, when the compiler met try-catch blocks injects some code blocks implicitly. In this way, we can manage try-catch blocks according to the our expectations.</p><p>Another topic we can talk about is runtime errors like dividing by zero or trying to access null pointer reference. This kind of errors mostly known as runtime errors. Apparently, runtime errors may not be managed by try catch blocks always. They can immediately occurs while program is running. If there is no handler for this kind of error types the program would be crash. On the other hand, if desired to catch runtime errors then they also should be able to handled.</p><p>So How could it be?</p><p>As mentioned above, for managed errors, the programmer starts try and catch blocks and when the compiler met these blocks injects some required codes as implicitly. Runtime errors differs during this time.</p><p><strong>1 — Runtime errors without try-catch blocks:</strong> Error handling mechanism not necessary but the programmer may want to know crash reason. The better option is handle this errors by default and crash again after clarifying error.</p><p><strong>2 — Runtime errors with try-catch blocks:</strong> The program must be able catch this errors and indirect program flow to user’s catch block.</p><p>For now, runtime errors handled for Unix like operating systems. The two type runtime errors above are handled in this way.</p><p>When the program initialized then some signal handlers are registered. For example SIGSEGV registered for null pointer exceptions because SIGSEGV usually occurs when we want to dereference a null pointer. Also SIGFPE for arithmetic errors like dividing by zero, and so on so forth.</p><p>This code clarify this situation I believe:</p><pre>// runtime.c<br><br>int main() {<br>    // by default we are pushing new env, so this way if user <br>    // don&#39;t add try catch blocks, this env recover and returns program after<br>    // handle exception<br>    // If programmer adds new try catch already pushes new env to stack and then that is used<br>    jmp_buf* env = push_env();<br>    val = setjmp(*env);<br>    if val != 0 {<br>      handle_exception();<br>      return val;<br>    }<br>    register_signal_handlers()<br>    program_main();<br>}<br><br>void register_signal_handlers() {<br>  signal(SIGSEGV, handle_signal);<br>  signal(SIGFPE, handle_signal);<br>  // ...<br>}<br><br>void handle_signal(int sig_code) {<br>    if (sig_code == SIGSEGV) <br>    else if (sig_code == SIGFPE)<br>    // ...<br>}</pre><p>All of the details gained me to observation about programming and I hope the experiences I learnt from this adventure will help me in the next projects future.</p><p>Let me know if I am mistaken.</p><p>Best regards.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=342b9e7406a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GRPC, Go ve Java ile Örnek Uygulama]]></title>
            <link>https://medium.com/piateamtech/grpc-go-ve-java-ile-%C3%B6rnek-uygulama-139e84a77d59?source=rss-5f121ac2a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/139e84a77d59</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rest]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[protobuf]]></category>
            <dc:creator><![CDATA[Niyazi Ekinci]]></dc:creator>
            <pubDate>Mon, 26 Apr 2021 18:59:25 GMT</pubDate>
            <atom:updated>2021-04-26T21:45:50.886Z</atom:updated>
            <content:encoded><![CDATA[<h3>GRPC - Go ve Java ile Örnek Uygulama</h3><p>Selamlar, bu yazımızda GRPC, Java ve Go ile örnek bir uygulama yapımına değineceğiz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VF7ZhOfVKAb8uCv68qlJDQ.jpeg" /><figcaption>GRPC, Go ve Java ile Örnek Uygulama</figcaption></figure><p>GRPC Google tarafından 2015–16 yıllarında open source olarak geliştirilen ve CNCF’e (Cloud Native Computing Foundation) bağışlanan bir RPC frameworküdür. CNCF’de mezunluğa aday projelerden birisidir. (<a href="https://www.cncf.io/projects/">https://www.cncf.io/projects/</a>)</p><p>Uygulamaya geçmeden önce Protocol Buffers ve GRPC’yi kısaca açıklamak gerekirse;</p><h4><strong>Protocol Buffers</strong></h4><p>Protocol Buffers, Interface Definition Language (IDL) ve serialization kütüphanesidir. Bu arayüz tanımlama dili ile mesajlarımızı ve servislerimizi tanımlayabiliyoruz. Daha sonra bu tanımladığımız servisler ve mesajları desteklenen diller için otomatik olarak üretebiliyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*rEHe-ym8gbiD8mLEfhPWZQ.png" /></figure><p>Protocol Buffers, (kısaca protobuf denilmekte) verileri serileştirmek ve deserileştirmek için JSON ve XML gibi yapısal veri türlerinin yerine binary tipini kullanan, mesajları binary’e dönüştürme protokolüdür. Yani verimli veri iletişimi, verilerin insan tarafından daha kolay bir şekilde okunabilmesine tercih edilmiştir. Bunun nedenini düşündüğümüzde aslında Google tarafından geliştirildiği için Google servislerini örnek verecek olursak saniyede milyonlarca verinin işlendiği bir ortamda JSON gibi field’ların isimlerinin bile byte’larca yer kapladığı bir serialization yapmak servislerde yavaşlamalara neden olabilir.</p><h4><strong>GRPC</strong></h4><p>Protocol Buffers’dan kısaca bahsettiğimize göre GRPC’ye geçebiliriz. GRPC HTTP2 üstüne geliştirilmiş olan bir Remote Call Procedure (RPC)’dir. Yani bir client bir servisteki kodu sanki kendi code base’indeymiş gibi çağırabilir. Contract’lara bağlı kod geliştirme söz konusudur. Önce arayüzlerimizi yazdıktan sonra ilgili dil için gerekli kodu üretiriz daha sonra üretilen fonksiyonumuzun içini doldururuz. GRPC unary, server stream, client stream ve bi-directional (bi-di) stream’i desteklemektedir. Sonuç olarak GRPC ile birlikte tek yönlü stream veya çift yönlü stream yapabilmekteyiz. Unary’i açıklamak gerekirse de kısaca request response modeli diyebiliriz.</p><p>REST’e göre avantajları ve dezavantajları mevcuttur. Kısaca farklarını inceleyecek olursak;</p><p>REST genellikle HTTP1.1 üstüne kurulmuş; GRPC ise HTTP2 üstüne kurulmuştur. HTTP1.1 ve HTTP2 arasındaki farklardan birine küçük bir örnek vermek gerekirse HTTP2&#39;de tek bir istekte birden fazla dosyayı alabilmekteyiz. HTTP1.1&#39;de ise her bir dosya için ayrı ayrı istek atıp TCP Handshake aşamalarından tek tek geçmemiz gerekiyor bu da bize network maliyeti olarak geri dönüyor.</p><p>GRPC’de contract first yaklaşımı mevcuttur. Önce arayüzleri tanımlamamız gerekiyor. Arayüzleri tanımladıktan sonra bu arayüzleri kullanarak kod üretebiliyoruz. İlgili dil için kodu ürettikten sonra kullanabiliyoruz. Örneğin bir yazılım geliştiricisi olarak yazdığımız bir servisteki bilgileri diğer servisten çağırmamız gerekiyor olsun ve servislerden biri Java diğeri .NET ile yazılmış olsun. Database entity’lerimizin tüm alanlarını paylaşmak istemeyiz bu durumda REST kullandığımızda Data Transfer Object’leri yazarız. Yani hem .NET servisinde hem de Java servisinde DTO yazmak durumunda kalmış oluruz. GRPC kullandığımızda ise herşey protofile’larda tanımlı olduğu için kodları proto compiler ile ürettiğimizde iki servis içinde buna sahip olacaktık. Servislerimiz eğer aynı dilde yazılsaydı bunu çözmek için DTO’larımızı common package altında tanımlamayı tercih edebilirdik ama bu da bize getirisinin yanında dil bağımlılığı olarak geri dönecekti.</p><p>REST’te endpointler mevcuttur. GRPC’de ise uzaktan fonksiyon çağrımı vardır. REST’te eğer OpenAPI kullanılmaz ise ve iki geliştirici aynı anda farklı servisleri geliştiriyorsa geliştiriciler birbiriyle iletişimde kalmak durumundadır. Servisi tüketecek olan diğer servis, istek atacağı kaynağın ayrıntılarına (url, metod, request payload ve response payload gibi) hakim olmalıdır ve ayrıca değişiklik durumunda da haberdar olmak zorundadır. Ayrıca herkese açık bir REST kaynağımız varsa değişiklik durumunda API’mizi versiyonlamak zorundayız. GRPC’de ise her şey önceden belgelendiği için geliştiriciler belgelenen arayüze uyarlar ve geliştiriciler arasında iletişim problemleri daha aza indirgenmiş olur.</p><p>Olaya internet tarayıcıları ve javascript tarafından bakacak olursak; Javascript native olarak JSON’u desteklemekte ve REST ile uyumlu çalışmakta REST bu kullanım senaryosunda güzel olabilir. Yine bunun yanında dış dünya ile iletişimde isek yani public bir API’mız var ise human-readable bir API yani JSON ile REST daha iyi bir fikir olabilir. GRPC ile yazılmış olan servislerimizin önüne API Gateway gibi bir katman koyarak browserların hizmetine verebilme seçeneğine de sahibiz. <br>Grpc’nin de browserlar için olan GRPC Web sürümü de var dilerseniz <a href="https://grpc.io/docs/platforms/web/basics/">buradan</a> ulaşabilirsiniz. GRPC daha çok mikro servisler arasındaki iletişimimiz için veya Android, IOS ve IOT uygulamalarımız için oldukça faydalıdır. Çünkü 4G ile internete bağlanan bir akıllı telefonda veri alış verişini minimize etmek kullanıcı açısından kota dostu bir uygulama olacaktır.</p><h4><strong>Örnek Uygulama</strong></h4><p>Şimdi sunucusunu java ile istemcisini ise golang ile yazacağımız bir örneği inceleyelim. Java kullanırken Spring Boot veya Quarkus ile de yazabilirdik. Ama bu örnekte direkt olarak java ile yazmayı tercih ettik.</p><pre><strong>syntax </strong>= <strong>&quot;proto3&quot;</strong>;<br><strong>option </strong>java_multiple_files = <strong>true</strong>;<br><strong>option </strong>go_package = <strong>&quot;user/&quot;</strong>;<br><strong>option </strong>java_package = <strong>&quot;com.example.grpc&quot;</strong>;<br><br><strong>message </strong>UserCreateRequest{<br>  <strong>string </strong>name = 1;<br>  <strong>string </strong>lastname = 2;<br>  <strong>int32  </strong>age = 3;<br>}<br><br><strong>message </strong>UserCreateResponse{<br>  <strong>string </strong>message = 1;<br>  <strong>bool </strong>ok = 2;<br>}<br><br><strong>service </strong>UserService{<br>  <strong>rpc </strong>create(UserCreateRequest) <strong>returns</strong>(UserCreateResponse);<br>}</pre><p>UserService.proto isimli dosyanın içerisine yukarıdaki tanımlamaları yapalım. Kısaca; Yukarıda UserService adında bir servis tanımladık. Bu servis UserCreateRequest tipinde mesaj alan ve UserCreateResponse tipinde bir mesaj dönen create adında unary rpc methoduna sahiptir. UserCreateRequest mesajının içinde name , lastname , age bilgilerini gönderiyoruz ve UserCreateResponse mesajının içinde message ve ok bilgilerini geri alıyoruz. IDL’in versiyonları olduğu için en üst satırda syntax’ımızın proto3 olması gerektiğini belirttik. <br>(Protocol buffers ve syntax hakkında daha detaylı bilgiye sahip olmak için <a href="https://developers.google.com/protocol-buffers/docs/proto3">bu link</a> üzerinden ulaşabilirsiniz)</p><p>Tanımlamaları yaptıktan sonra sunucumuzu yazmak için boş bir maven projesi oluşturalım. pom.xml dosyasına aşağıdaki dependencyleri eklememiz gerekiyor.</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>    &lt;artifactId&gt;grpc-netty-shaded&lt;/artifactId&gt;<br>    &lt;version&gt;1.37.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>    &lt;artifactId&gt;grpc-protobuf&lt;/artifactId&gt;<br>    &lt;version&gt;1.37.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>    &lt;groupId&gt;io.grpc&lt;/groupId&gt;<br>    &lt;artifactId&gt;grpc-stub&lt;/artifactId&gt;<br>    &lt;version&gt;1.37.0&lt;/version&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt; &lt;!-- necessary for Java 9+ --&gt;<br>    &lt;groupId&gt;org.apache.tomcat&lt;/groupId&gt;<br>    &lt;artifactId&gt;annotations-api&lt;/artifactId&gt;<br>    &lt;version&gt;6.0.53&lt;/version&gt;<br>    &lt;scope&gt;provided&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>Yukarıda yazmış olduğumuz proto dosyasını derlemek için yine pom.xml dosyasına aşağıdaki pluginleri ekleyelim.</p><pre>&lt;build&gt;<br>    &lt;extensions&gt;<br>        &lt;extension&gt;<br>            &lt;groupId&gt;kr.motd.maven&lt;/groupId&gt;<br>            &lt;artifactId&gt;os-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;1.6.2&lt;/version&gt;<br>        &lt;/extension&gt;<br>    &lt;/extensions&gt;<br>    &lt;plugins&gt;<br>        &lt;plugin&gt;<br>            &lt;groupId&gt;org.xolstice.maven.plugins&lt;/groupId&gt;<br>            &lt;artifactId&gt;protobuf-maven-plugin&lt;/artifactId&gt;<br>            &lt;version&gt;0.6.1&lt;/version&gt;<br>            &lt;configuration&gt;<br>                &lt;protocArtifact&gt;com.google.protobuf:protoc:3.12.0:exe:${os.detected.classifier}&lt;/protocArtifact&gt;<br>                &lt;pluginId&gt;grpc-java&lt;/pluginId&gt;<br>                &lt;pluginArtifact&gt;io.grpc:protoc-gen-grpc-java:1.37.0:exe:${os.detected.classifier}&lt;/pluginArtifact&gt;<br>            &lt;/configuration&gt;<br>            &lt;executions&gt;<br>                &lt;execution&gt;<br>                    &lt;goals&gt;<br>                        &lt;goal&gt;compile&lt;/goal&gt;<br>                        &lt;goal&gt;compile-custom&lt;/goal&gt;<br>                    &lt;/goals&gt;<br>                &lt;/execution&gt;<br>            &lt;/executions&gt;<br>        &lt;/plugin&gt;<br>    &lt;/plugins&gt;<br>&lt;/build&gt;</pre><p>Daha sonra mvn clean install yaparak dependencylerin yüklenmesini bekleyelim. Dependencyler yüklendikten sonra src/main/proto klasörünün altına UserService.proto dosyamızı kopyalayalım. Yani dosya yapımız aşağıdaki gibi olmalıdır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*vgbexdMmkZsZvs4Gzb67LA.png" /><figcaption>Proto klasörü</figcaption></figure><p>Bütün bunları yaptıktan sonra terminal üzerinden mvn compile komutunu çalıştıralım. Bu komutu çalıştırdıktan sonra proto compiler yazmış olduğumuz UserService.proto dosyasını okuyarak bizim için implemente edilmeyi bekleyen classlarımızı oluşturacaktır. İlgili classları oluşan target klasörünün altında görebilirsiniz. Daha sonra java klasörünün içine UserServiceImpl class’ını ekleyelim. Ardından aşağıdaki gibi düzenlemeleri yapalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4575a7650e567224a444ac7277c49aba/href">https://medium.com/media/4575a7650e567224a444ac7277c49aba/href</a></iframe><p>Otomatik olarak ürettiğimiz class’ı UserServiceImpl class’ında extends ediyoruz. Daha sonra create metodunu override ediyoruz ve içini dolduruyoruz. Proto dosyasında tanımladığımız gibi UserCreateResponse nesnesini oluşturuyoruz. Üretilen kod bizim için builder patterni de uyguluyor. Daha sonra responseObserver.onNext(response) ve responseObserver.onCompleted() kodlarını yazarak response’un client’a gönderilmesini sağlıyoruz. Şimdi java klasörünün içine GrpcServer adında bir class daha oluşturalım. Ve aşağıdaki düzenlemeleri yapalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de3f036322f47d7397490141ce0f9f33/href">https://medium.com/media/de3f036322f47d7397490141ce0f9f33/href</a></iframe><p>Bu yazdığımız class’da kısaca 9090 portunda bir uygulama çalıştırmasını ve requestleri kabul etmesi gerektiğini belirttik. Şimdi Golang ile client yazımına geçebiliriz.</p><p>Öncelikle proto compiler yüklememiz gerekiyor. Ben homebrew üzerinden yükledim siz dilerseniz <a href="https://developers.google.com/protocol-buffers/docs/downloads">bu link üzerinden yükleyebilirsiniz.</a> Proto-compiler yükledikten sonra bir tane go mod projesi oluşturalım. go.mod dosyasının içini aşağıdaki gibi dolduralım.</p><pre><strong>module </strong>grpc.example.com/user-client<br><br><strong>go </strong>1.16<br><br><strong>require </strong>(<br>   <strong>github.com/golang/protobuf </strong>v1.5.2 <em>// indirect<br>   </em><strong>golang.org/x/net </strong>v0.0.0-20210423184538-5f58ad60dda6 <em>// indirect<br>   </em><strong>golang.org/x/sys </strong>v0.0.0-20210423185535-09eb48e85fd7 <em>// indirect<br>   </em><strong>google.golang.org/genproto </strong>v0.0.0-20210423144448-3a41ef94ed2b <em>// indirect<br>   </em><strong>google.golang.org/grpc </strong>v1.37.0 <em>// indirect<br>   </em><strong>google.golang.org/protobuf </strong>v1.26.0 <em>// indirect<br></em>)</pre><p>Daha sonra terminalden go mod download komutunu çalıştıralım. UserService.proto dosyasını ana dizinimize kopyalayalım. Bu işlemden sonra protoc --go_out=plugins=grpc:. UserService.proto komutunu çalıştıralım. user klasörü altında bizim için kodun üretildiğini görebiliriz. Daha sonra main.go adında bir dosya oluşturalım ve içini aşağıdaki gibi dolduralım.</p><pre><strong>package </strong>main<br><br><strong>import </strong>(<br>   <strong>&quot;context&quot;<br>   &quot;fmt&quot;<br>   &quot;google.golang.org/grpc&quot;<br>   &quot;grpc.example.com/user-client/user&quot;<br>   &quot;log&quot;<br></strong>)<br><br><strong>func </strong>main()  {<br>   conn, err := grpc.Dial(<strong>&quot;localhost:9090&quot;</strong>, grpc.WithInsecure())<br>   <strong>if </strong>err != nil{<br>      log.Fatalf(<strong>&quot;Hata oluştu: %s&quot;</strong>, err)<br>   }<br>   <strong>defer </strong>conn.Close()<br>   userService := user.NewUserServiceClient(conn)<br>   resp, err := userService.Create(context.Background(), &amp;user.UserCreateRequest{<br>      Name:     <strong>&quot;Foo&quot;</strong>,<br>      Lastname: <strong>&quot;Bar&quot;</strong>,<br>      Age:      23,<br>   })<br>   <br>   <strong>if </strong>err != nil {<br>   log.Printf(<strong>&quot;Bir sorun oluştu: %s&quot;</strong>, err)<br>   }</pre><pre>   fmt.Print(resp)<br><br>}</pre><p>Her şey düzgün çalıştığında ekranda message:”Kullanıcı oluşturuldu: Foo Bar” ok:true şeklinde bir çıktı olması gerekir. Burada öncelikle localhost:9090 üstünde çalışan servera bağlantı kuruyoruz ve userService.Create fonksiyonunu sanki kendi ortamımızdaymış gibi çağırıyoruz. Aslında Java tarafında yazmış olduğumuz kod çalışmış oldu.</p><p>Özetle; GRPC kullanım senaryolarına bağlı olarak REST’e güzel bir alternatiftir tabi günün sonunda her uygulamanın kendi ihtiyacı ve gereklilikleri vardır. Bu gereklilikler geliştirici ekibi, müşteri kitlesi, uygulama türü, projenin yetişmesi gereken zaman ve bilgi birikimi gibi daha bir sürü etkenlerle tartılarak belirlenmelidir.</p><p>GRPC ve Protocol Buffers’a benzer olarak ise Apache Thrift kullanımı söz konusu olabilir. Apache Thrift ise Facebook tarafından geliştirilip Apache Foundation’a bağışlanmıştır. (<a href="https://thrift.apache.org/">bkz</a>)</p><p>Şimdilik GRPC’yi biraz olsun anlamak için yazdığımız bu yazımızın sonuna gelmiş bulunmaktayız.</p><p>Vakit ayırıp okuduğunuz için teşekkürler.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=139e84a77d59" width="1" height="1" alt=""><hr><p><a href="https://medium.com/piateamtech/grpc-go-ve-java-ile-%C3%B6rnek-uygulama-139e84a77d59">GRPC, Go ve Java ile Örnek Uygulama</a> was originally published in <a href="https://medium.com/piateamtech">Pia-Team Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring Boot ve React ile Url Kısaltıcı Yapımı]]></title>
            <link>https://niyaziekinci.medium.com/spring-boot-ve-react-ile-url-k%C4%B1salt%C4%B1c%C4%B1-yap%C4%B1m%C4%B1-bf327368e2f7?source=rss-5f121ac2a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf327368e2f7</guid>
            <dc:creator><![CDATA[Niyazi Ekinci]]></dc:creator>
            <pubDate>Mon, 08 Feb 2021 07:07:48 GMT</pubDate>
            <atom:updated>2021-02-08T08:14:38.516Z</atom:updated>
            <content:encoded><![CDATA[<p>Selamlar,</p><p>Bugün Spring Boot, React ve Nginx kullanarak URL kısaltıcı yapımına değineceğiz.</p><p>Öncelikle uygulamanın temel yapısından bahsetmek istiyorum. Uygulamamız bilinen URL kısaltıcılarda olduğu gibi, kaydedilmek istenen uzun bir url’i daha kısa bir url ile eşleştiren, kısa url’e erişilmek istendiğinde ise uzun url’e yönlendirme yapılmasını sağlayan bir uygulamadır.</p><p>Bu nedenle uygulamamızda url’leri saklayabilmek için Spring Boot ile servis yazacağız. Projeye başlamadan önce projenin çalışır halini görmek isterseniz <a href="http://niceurl.live/">bu </a>adresi ziyaret edebilirsiniz.</p><h4>Servisimizi yazalım</h4><p>Öncelikle maven projesi oluşturmakla başlayalım. Maven projemizi oluşturduğumuzda bağımlılıkların tam ve eksiksiz yüklenmesi için aşağıdaki pom.xml dosyasını pom.xml dosyamızla değiştirelim.</p><pre><em>&lt;?</em><strong>xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;</strong><em>?&gt;<br></em>&lt;<strong>project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;<br>         xsi:schemaLocation=&quot;http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd&quot;</strong>&gt;<br>    &lt;<strong>modelVersion</strong>&gt;4.0.0&lt;/<strong>modelVersion</strong>&gt;<br>    &lt;<strong>parent</strong>&gt;<br>        &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>        &lt;<strong>artifactId</strong>&gt;spring-boot-starter-parent&lt;/<strong>artifactId</strong>&gt;<br>        &lt;<strong>version</strong>&gt;2.3.7.RELEASE&lt;/<strong>version</strong>&gt;<br>        &lt;<strong>relativePath</strong>/&gt; <em>&lt;!-- lookup parent from repository --&gt;<br>    </em>&lt;/<strong>parent</strong>&gt;<br>    &lt;<strong>groupId</strong>&gt;com.app&lt;/<strong>groupId</strong>&gt;<br>    &lt;<strong>artifactId</strong>&gt;urlshortener&lt;/<strong>artifactId</strong>&gt;<br>    &lt;<strong>version</strong>&gt;0.0.1&lt;/<strong>version</strong>&gt;<br>    &lt;<strong>name</strong>&gt;urlshortener&lt;/<strong>name</strong>&gt;<br>    &lt;<strong>description</strong>&gt;URL Shortener&lt;/<strong>description</strong>&gt;<br>    &lt;<strong>properties</strong>&gt;<br>        &lt;<strong>java.version</strong>&gt;1.8&lt;/<strong>java.version</strong>&gt;<br>        &lt;<strong>spring-cloud.version</strong>&gt;Hoxton.SR9&lt;/<strong>spring-cloud.version</strong>&gt;<br>        &lt;<strong>start-class</strong>&gt;com.app.urlshortener.UrlShortenerApplication&lt;/<strong>start-class</strong>&gt;<br>    &lt;/<strong>properties</strong>&gt;<br><br>    &lt;<strong>dependencies</strong>&gt;<br>        &lt;<strong>dependency</strong>&gt;<br>            &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>            &lt;<strong>artifactId</strong>&gt;spring-boot-starter-data-mongodb&lt;/<strong>artifactId</strong>&gt;<br>        &lt;/<strong>dependency</strong>&gt;<br>        &lt;<strong>dependency</strong>&gt;<br>            &lt;<strong>groupId</strong>&gt;org.projectlombok&lt;/<strong>groupId</strong>&gt;<br>            &lt;<strong>artifactId</strong>&gt;lombok&lt;/<strong>artifactId</strong>&gt;<br>            &lt;<strong>optional</strong>&gt;true&lt;/<strong>optional</strong>&gt;<br>        &lt;/<strong>dependency</strong>&gt;<br>        &lt;<strong>dependency</strong>&gt;<br>            &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>            &lt;<strong>artifactId</strong>&gt;spring-boot-starter-test&lt;/<strong>artifactId</strong>&gt;<br>            &lt;<strong>scope</strong>&gt;test&lt;/<strong>scope</strong>&gt;<br>        &lt;/<strong>dependency</strong>&gt;<br>        &lt;<strong>dependency</strong>&gt;<br>            &lt;<strong>groupId</strong>&gt;org.apache.commons&lt;/<strong>groupId</strong>&gt;<br>            &lt;<strong>artifactId</strong>&gt;commons-lang3&lt;/<strong>artifactId</strong>&gt;<br>        &lt;/<strong>dependency</strong>&gt;<br>        &lt;<strong>dependency</strong>&gt;<br>            &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>            &lt;<strong>artifactId</strong>&gt;spring-boot-starter-web&lt;/<strong>artifactId</strong>&gt;<br>        &lt;/<strong>dependency</strong>&gt;<br>    &lt;/<strong>dependencies</strong>&gt;<br>    &lt;<strong>dependencyManagement</strong>&gt;<br>        &lt;<strong>dependencies</strong>&gt;<br>            &lt;<strong>dependency</strong>&gt;<br>                &lt;<strong>groupId</strong>&gt;org.springframework.cloud&lt;/<strong>groupId</strong>&gt;<br>                &lt;<strong>artifactId</strong>&gt;spring-cloud-dependencies&lt;/<strong>artifactId</strong>&gt;<br>                &lt;<strong>version</strong>&gt;${spring-cloud.version}&lt;/<strong>version</strong>&gt;<br>                &lt;<strong>type</strong>&gt;pom&lt;/<strong>type</strong>&gt;<br>                &lt;<strong>scope</strong>&gt;import&lt;/<strong>scope</strong>&gt;<br>            &lt;/<strong>dependency</strong>&gt;<br>        &lt;/<strong>dependencies</strong>&gt;<br>    &lt;/<strong>dependencyManagement</strong>&gt;<br><br>    &lt;<strong>build</strong>&gt;<br>        &lt;<strong>pluginManagement</strong>&gt;<br>            &lt;<strong>plugins</strong>&gt;<br>                &lt;<strong>plugin</strong>&gt;<br>                    &lt;<strong>groupId</strong>&gt;org.springframework.boot&lt;/<strong>groupId</strong>&gt;<br>                    &lt;<strong>artifactId</strong>&gt;spring-boot-maven-plugin&lt;/<strong>artifactId</strong>&gt;<br>                    &lt;<strong>configuration</strong>&gt;<br>                        &lt;<strong>excludes</strong>&gt;<br>                            &lt;<strong>exclude</strong>&gt;<br>                                &lt;<strong>groupId</strong>&gt;org.projectlombok&lt;/<strong>groupId</strong>&gt;<br>                                &lt;<strong>artifactId</strong>&gt;lombok&lt;/<strong>artifactId</strong>&gt;<br>                            &lt;/<strong>exclude</strong>&gt;<br>                        &lt;/<strong>excludes</strong>&gt;<br>                    &lt;/<strong>configuration</strong>&gt;<br>                   <br>                &lt;/<strong>plugin</strong>&gt;<br>            &lt;/<strong>plugins</strong>&gt;<br>        &lt;/<strong>pluginManagement</strong>&gt;<br>    &lt;/<strong>build</strong>&gt;<br>    &lt;<strong>repositories</strong>&gt;<br>        &lt;<strong>repository</strong>&gt;<br>            &lt;<strong>id</strong>&gt;spring-milestones&lt;/<strong>id</strong>&gt;<br>            &lt;<strong>name</strong>&gt;Spring Milestones&lt;/<strong>name</strong>&gt;<br>            &lt;<strong>url</strong>&gt;https://repo.spring.io/milestone&lt;/<strong>url</strong>&gt;<br>        &lt;/<strong>repository</strong>&gt;<br>    &lt;/<strong>repositories</strong>&gt;<br><br>&lt;/<strong>project</strong>&gt;</pre><p>Bu değişikliği yaptıktan sonra komut satırından <em>mvn clean install</em> yaparak bağımlılıkların yüklenmesini sağlayalım. Daha sonra com.app.urlshortener paketinin altına Spring Boot main class’ımızı oluşturalım. Aşağıdaki gibi görünmesi gerekiyor;</p><pre><strong>package </strong>com.app.urlshortener;<br><br><strong>import </strong>org.springframework.boot.SpringApplication;<br><strong>import </strong>org.springframework.boot.autoconfigure.SpringBootApplication;<br><br>@SpringBootApplication<br><strong>public class </strong>UrlShortenerApplication {<br><br>    <strong>public static void </strong>main(String[] args) {<br>        SpringApplication.run(UrlShortenerApplication.<strong>class</strong>, args);<br>    }<br>}</pre><p>Bu class ile birlikte Spring Boot uygulamamızın başlangıcı sağlanacaktır. Daha sonra url’lerimizi veritabanında modellemek ve maplemek için Link sınıfımızı oluşturalım. <em>com.app.urlshortener.model</em> paketinin altına Link adında bir sınıf oluşturalım ve aşağıdaki field’ları class’ımıza ekleyelim.</p><pre>@Data<br><strong>public class </strong>Link {<br>    @Id<br>    <strong>private </strong>String <strong>id</strong>;<br>    <strong>private </strong>String <strong>url</strong>;<br>    <strong>private </strong>String <strong>shortUrl</strong>;<br>    @CreatedDate<br>    <strong>private </strong>Date <strong>createDate</strong>;<br>}</pre><p>@Data annotationuyla birlikte pom.xml dosyasında belirtmiş olduğumuz Lombok kütüphanesinin özelliklerinden faydalanıyoruz @Data annotation’u bize field’ların getter ve setterlar’ının otomatik üretilmesini sağlıyor. Link modelimizi yazdığımıza göre Spring Data JPA MongoDB kütüphanesinin soyutlamasından yararlanarak veritabanı repository katmanını oluşturalım. Ama öncelikle veritabanı bağlantı stringimizi resources altında application.yml dosyasına ekleyelim.</p><pre><strong>server</strong>:<br>  <strong>port</strong>: 6060<br><strong>spring</strong>:<br>  <strong>application</strong>:<br>    <strong>name</strong>: urlshortener-service<br>  <strong>data</strong>:<br>    <strong>mongodb</strong>:<br>      <strong>uri</strong>: ************************</pre><p><strong>uri </strong>için kendi veritabanı bağlantı stringimizi yazalım. Ardından repository katmanından devam edelim. <em>com.app.urlshortener.repository</em> paketinin altına LinkRepository interface’imizi oluşturalım.</p><pre>@Repository<br><strong>public interface </strong>LinkRepository <strong>extends </strong>MongoRepository&lt;Link, String&gt; {<br>    Link findByShortUrl(String shortUrl);<br>    <strong>boolean </strong>existsByShortUrl(String shortUrl);<br>}</pre><p>@Repository annotation’uyla işaretlediğimiz LinkRepository interface’imiz MongoRepository&lt;Link, String&gt; interface’ini extend etmektedir. Bu sayede spring boot bizim için interface’imizi concrete ederek inject edecektir. Burada interface üzerinde tanımladığımız querylerde yine bizim için oluşturulacaktır. Örneğin, findByShortUrl bize shortUrl’e göre veritabanında eğer varsa veri getirecektir.</p><p>Daha sonra bu repository’i kullanacağımız servis katmanını kodlamaya geçelim. Öncelikle <em>com.app.urlshortener.service </em>paketinin içine LinkService class’ımızı oluşturalım.</p><pre>@Service<br><strong>public class </strong>LinkService {</pre><pre>}</pre><p>Sınıfımızı oluşturduk, @Service annotationu Spring Boot’a bu class’ın dependency injection için kullanılabileceğini söylüyor Yani bir üst katmanda @Autowired yazarak erişebilmemizi sağlıyor.</p><p>Burada az önce oluşturmuş olduğumuz repository interface’ini inject edelim.</p><pre>@Autowired <strong>private </strong>LinkRepository <strong>repository</strong>;</pre><p>Inject ettikten sonra ilk başta uzun url’i kısa url’e çeviren generate metodumuzu yazalım.</p><pre><strong>public </strong>String generate(String url){<br>    <strong>if </strong>(!url.startsWith(<strong>&quot;http&quot;</strong>)){<br>        url = <strong>&quot;http://&quot; </strong>+ url;<br>    }<br>    String shortUrl = generateHelper(url);<br>    Link link = <strong>new </strong>Link();<br>    link.setCreateDate(<strong>new </strong>Date());<br>    link.setId(UUID.<em>randomUUID</em>().toString());<br>    link.setShortUrl(shortUrl);<br>    link.setUrl(url);<br>    <strong>repository</strong>.save(link);<br>    <strong>return </strong>shortUrl;<br>}</pre><p>Url’miz eğer http ile başlamıyor ise url’in başına http ekleyerek tam bir link olmasını sağlıyoruz ki http yönlendirmesi yaptığımızda doğru sonucu elde edelim. Daha sonra <em>generateHelper</em><strong> </strong>isimli metodumuzu çağırıyoruz. Generate helper bize 6 harften oluşan <strong>abcdefghjklmnoprstuvyzwx1234567890 </strong>karakterlerini içeren rasgele karakter dizisi üretmek için yardım ediyor. Stringimizi ürettikten sonra veritabanına kaydediyoruz.</p><pre><strong>private </strong>String generateHelper(String url){<br>    String geneatedUrl = RandomStringUtils.<em>random</em>(6, <strong>&quot;abcdefghjklmnoprstuvyzwx1234567890&quot;</strong>);<br>    <strong>boolean </strong>exists = <strong>repository</strong>.existsByShortUrl(geneatedUrl);<br>    <strong>if </strong>(exists){<br>        <strong>return </strong>generateHelper(url);<br>    }<br>    <strong>return </strong>geneatedUrl;<br>}</pre><p>Daha sonra kısa url ile sistemimize istek yapıldığında uzun url’e yönlendirme yapmak için gerekli servis metodunu yazıyoruz.</p><pre><strong>public void </strong>get(HttpServletResponse response, String url){<br>    Link get = <strong>repository</strong>.findByShortUrl(url);<br>    <strong>if </strong>(Objects.<em>nonNull</em>(get)) {<br>        response.setStatus(301);<br>        response.addHeader(<strong>&quot;Location&quot;</strong>, get.getUrl());<br>        <strong>return</strong>;<br>    }<br>    response.setStatus(301);<br>    response.addHeader(<strong>&quot;Location&quot;</strong>, <strong>&quot;404&quot;</strong>);<br>}</pre><p>Burada servisimize bir üst katmandan gelen HttpServletResponse nesnesi bize http response’una müdahale etmeyi sağlamış oluyor. Url ise veritabanında sorgulayacağımız kısaltılmış url’e karşılık gelmektedir. Veritabanına istek attıktan sonra eğer sonuç döner ise <strong>HTTP 301 Kalıcı Yönlendirme </strong>ile kullanıcıyı uzun url’e yönlendirmiş olacağız.</p><p><em>response.setStatus(301) </em>ile http durum kodunu belirledik, <em>response.addHeader(“Location”, get.getUrl())</em> ile de yönlendirme yapmak istediğimiz URL’i verdik. Eğer veritabanından veri dönmezse 404 sayfasına yönlendirme yaptırdık. Böylelikle 301 kodunu ve Location olarak belirtilmiş URL’i alan tarayıcılar belirtilen url’e yönlendirme yapacaklardır.</p><p>Daha sonra dış uygulamalarla aramızdaki sözleşme olan API katmanını yazmaya başlayalım. Uygulamamız oldukça basit bir uygulama olduğu için 2 tane endpointi olan bir api sınıfı oluşturalım. <em>com.app.urlshortener.api </em>paketi altına LinkApi adında bir sınıf oluşturalım.</p><pre>@RestController<br>@RequestMapping(<strong>&quot;/urlshortener&quot;</strong>)<br>@CrossOrigin<br><strong>public class </strong>LinkApi {</pre><pre>}</pre><p>HTTP isteklerini karşılayacağımız katman class’ını oluşturduktan sonra endpointleri yazalım. Öncelikle url’imizi kısaltacağımız endpoint’i yazalım. Fakat burada endpointi yazmadan önce az önce yazdığımız servis katmanını sınıfımıza inject edelim.</p><pre>@Autowired <strong>private </strong>LinkService service;</pre><p>@Autowired annotation’uyla işaretlediğimiz LinkService class’ını Spring Boot bize kullanabilmemiz için inject edecektir. Şimdi kaldığımız yerden devam edelim http post metodu ve /urlshortener/generate path’iyle gelen isteklerin yeni URL oluşturmasını istiyoruz bu nedenle aşağıdaki metodu yazmamız gerekiyor.</p><pre>@PostMapping(<strong>&quot;/generate&quot;</strong>)<br><strong>public </strong>String generate(@RequestBody String url){<br>   <strong>return </strong>service.generate(url);<br>}</pre><p>Request Body’sine string şeklinde yazılan URL’in geriye string döndürmesi bekleniyor bir alt katmanda bu sözleşmeyi yerine getiren kodumuzu az önce yazdık şimdi buradan o metodu kullanarak client’e cevap dönüyoruz.</p><p>Son endpoint olan, generate edilen url’e yönlendiren, metodumuzu yazalım. Http get ve /urlshortener/{url} şeklinde gelen isteklerin gerçek url’e yönlendirme yapmasını istiyoruz.</p><pre>@GetMapping(<strong>&quot;/{url}&quot;</strong>)<br><strong>public void </strong>get(HttpServletResponse response, @PathVariable(<strong>&quot;url&quot;</strong>) String url){<br>  <strong>service</strong>.get(response, url);<br>}</pre><p>Burada HttpServletResponse nesnesinin spring tarafından inject edilmesini istedik çünkü response üzerinden varsa gerçek url’e HTTP 301 kalıcı yönlendirmesi yapacağız. Sınıfımızın son hali aşağıdaki gibidir.</p><pre>@RestController<br>@RequestMapping(<strong>&quot;/urlshortener&quot;</strong>)<br>@CrossOrigin<br><strong>public class </strong>LinkApi {<br><br>    @Autowired <strong>private </strong>LinkService service;<br><br>    @PostMapping(<strong>&quot;/generate&quot;</strong>)<br>    <strong>public </strong>String generate(@RequestBody String url){<br>       <strong>return </strong>service.generate(url);<br>    }<br><br>    @GetMapping(<strong>&quot;/{url}&quot;</strong>)<br>    <strong>public void </strong>get(HttpServletResponse response, @PathVariable(<strong>&quot;url&quot;</strong>) String url){<br>      service.get(response, url);<br>    }<br>}</pre><p>Servis katmanında yazdığımız kodumuzu api katmanından dış dünyaya açtığımıza göre şimdi önyüz kodlamasına geçelim.</p><h4>Önyüz kodlaması</h4><p>Önyüzde React kütüphanesini kullanacağımız için öncelikle npm ve node.js’in kurulu olduğundan emin olduktan sonra npx create-react-app frontendkomutunu çalıştıralım. Daha sonra ise react-material kütüphanesini yükleyelim.</p><pre>npm i @material-ui/core --save<br>npm i @material-ui/icons --save</pre><p>Ardından yine bağımlılığımız olan react-router-dom kütüphanesini kuralım.</p><pre>npm i react-router-dom --save</pre><p>Daha sonra create-react-app ile gelen App.js dosyamızın içini temizleyelim ve react-router-dom kütüphanesinden gelen router’imizi import edelim. Böylelikle routing işlemlerimizi yapabilmiş olacağız.</p><pre>import {<br>    BrowserRouter as Router,<br>    Switch,<br>    Route,<br>    Link<br>} from &quot;react-router-dom&quot;;</pre><p>Import ettikten sonra App.js dosyamızı aşağıdaki gibi dolduralım.</p><pre>const <em>App </em>= () =&gt; {<br>  <br>  return (<br>    &lt;Router&gt;<br>      &lt;Switch&gt;<br>          &lt;Route exact path=&quot;/&quot;&gt;<br>              &lt;IndexPage/&gt;<br>          &lt;/Route&gt;<br>          &lt;Route exact path=&quot;/404&quot;&gt;<br>              &lt;div style={{display: &#39;flex&#39;, justifyContent: &#39;center&#39;, alignItems:&#39;center&#39;, height: &#39;100vh&#39;, fontSize: &#39;24px&#39;}}&gt;404 - Not Found&lt;/div&gt;<br>          &lt;/Route&gt;<br>      &lt;/Switch&gt;<br>    &lt;/Router&gt;<br>  );<br>}<br><br>export default <em>App</em>;</pre><p>Router ve Switch componentleri altına yazmış olduğumuz route’lar her biri bir sayfa olmak üzere url’lerimizi tanımlamaktadır. <strong>exact</strong> props’u tam olarak eşleşme sağlandığında route içindeki component’in çalıştırılması gerektiğini belirtmektedir. Burada IndexPage adlı bir tane daha componentimiz var bu component’i şimdi kodlamaya başlayacağız.</p><p>src klasörünün altına pages adında bir klasör oluşturalım ve içinde index.js adlı bir dosya oluşturalım ardından index.styles.js adında bir dosya daha oluşturalım style’ları react-material’ın sağlamış olduğu api üzerinden yazacağız.</p><p>index.js dosyamızı açalım ardından aşağıdaki fonksiyonu yazalım.</p><pre>const <em>IndexPage </em>= () =&gt; {<br>  <br>}</pre><pre>export default IndexPage;</pre><p>Önce gerekli olan import işlemlerini yapalım.</p><pre>import React from &quot;react&quot;;<br>import {Container, Link, Typography} from &quot;@material-ui/core&quot;;<br>import useStyles from &quot;./index.styles&quot;;<br>import <em>UrlShortener </em>from &quot;../components/url-shortener/url-shortener&quot;;</pre><p>Buradaki UrlShortener’i az sonra kodlamaya başlayacağız. Şimdi componentimizin içini bu şekilde dolduralım;</p><pre>const <em>IndexPage </em>= () =&gt; {<br>    const classes = useStyles();<br>    React.<em>useEffect</em>(() =&gt; {<br>       document.title = &quot;Url Shortener&quot;;<br>    }, []);</pre><pre>    return (<br>        &lt;Container className={classes.main} maxWidth=&quot;md&quot;&gt;<br>            &lt;div className={classes.root}&gt;<br>                &lt;Link href=&quot;/&quot;&gt;&lt;Typography color=&quot;secondary&quot;&gt;URL Shortener&lt;/Typography&gt;&lt;/Link&gt;<br>            &lt;/div&gt;<br>            &lt;div className={classes.container}&gt;<br>                &lt;Typography variant=&quot;h2&quot;&gt;URL Shortener&lt;/Typography&gt;<br>                &lt;Typography color=&quot;primary&quot;&gt;Nice URL, shorten long URLs.&lt;/Typography&gt;<br>                &lt;UrlShortener /&gt;<br>            &lt;/div&gt;<br>        &lt;/Container&gt;<br>    )<br>}</pre><p>Yukarıdaki kodu açıklamak gerekirse index.styles.js dosyasında yazmış olduğumuz css’i useStyles olarak componentimize import ettik ardından componentimizin içinde const classes = useStyles(); şeklinde kullanmaya hazır hale getirdik. Daha sonra React.useEffect içinde sayfamızın browserda görünecek olan başlığını ayarladık. Container componenti ile sayfamızı sarmaladık maxWidth=”md” props’una sahip olan componentimiz sayfanın içeriğini belirli bir boyuta getirip ortalayacaktır. Bu class’a index.styles.js içinde yazmış olduğumuz main css sınıfını vermiş olduk. Daha sonra üst menüye sahip olmak için bir altına div oluşturup sol üst tarafa yerleşecek olan Link’imizi verdik. Ardından iç container olarak nitelendirdiğimiz div’in içinde sitemizde görünecek olan başlıkları ve UrlShortener componentini çağırıyoruz.</p><pre>import <em>makeStyles </em>from &quot;@material-ui/core/styles/makeStyles&quot;;<br><br>const useStyles = <em>makeStyles</em>({<br>    main: {<br>        display: &#39;grid&#39;,<br>        gridTemplateRows: &#39;auto 1fr&#39;,<br>        height: &#39;100vh&#39;<br>    },<br>    root: {<br>        width: &#39;100%&#39;,<br>        fontSize: &#39;large&#39;,<br>        display: &#39;flex&#39;,<br>        padding: &#39;20px 0&#39;,<br>        flex: &#39;1 0 auto&#39;,<br>        justifyContent: &#39;space-between&#39;<br>    },<br>    container: {<br>        display: &#39;flex&#39;,<br>        flexDirection: &#39;column&#39;,<br>        gap: &#39;20px&#39;,<br>        paddingTop: &#39;120px&#39;<br>    },<br>    h1: {<br>        fontSize: &#39;64px&#39;,<br>        fontWeight: &#39;bolder&#39;<br>    }<br>});<br><br>export default useStyles;</pre><p>index.js dosyasında kullanmış olduğumuz style class’ları yukarıdaki gibidir. Şimdi UrlShortener component’ini yazmaya başlayalım. Öncelikle src klasörünün altına components adında bir klasör oluşturalım daha sonra url-shortener adında bir klasör daha oluşturup içinde url-shortener.js ve url-shortener.styles.js adında dosyalar oluşturalım. url-shortener.js dosyamızı aşağıdaki gibi ilklendirelim.</p><pre>const <em>UrlShortener </em>= () =&gt; {<br><br>    const classes = useStyles();<br>}<br>export default UrlShortener;</pre><p>Daha sonra React hookları kullanarak aşağıdaki state’lerimizi oluşturalım.</p><pre>const [result, setResult] = React.<em>useState</em>(null);</pre><p>Bu state’imiz servise göndermiş olduğumuz uzun url’in sonucunda dönen kısa url’i tutmak için kullanılmaktadır.</p><pre>const [baseUrl, setBaseUrl] = React.<em>useState</em>(&#39;&#39;);</pre><p>Bu state ise servise göndermiş olduğumuz uzun url’i tutmaktadır.</p><pre>const [loading, setLoading] = React.<em>useState</em>(false);<br>const [error, setError] = React.<em>useState</em>(false);</pre><p>Bu iki state’den loading servise istek yapıldığında true olarak setlenecek ve ekranda loading iconu görüntülenmesini sağlayacaktır. Servisten response döndüğünde ise false olarak setlenecek ve sonucun görüntülenmesini sağlayacaktır. Error state’i ise hata olması durumunda ekranda hatayı basmak için kullanılmaktadır.</p><pre>const [copied, setCopied] = React.<em>useState</em>(false);</pre><p>Son olarak copied state’i ekranda çıkan url’i buton ile kopyaladıktan sonra copied uyarısının 1100 ms ekranda görünmesini sağlamak için kullanılacaktır.</p><pre>const copyURL = () =&gt; {<br>    const resultTextField = document.getElementById(&#39;result-textfield&#39;);<br>    resultTextField.focus();<br>    resultTextField.select();<br>    try {<br>        document.execCommand(&#39;copy&#39;);<br>    } catch (err) {<br>        console.error(&#39;Oops, unable to copy&#39;);<br>    }<br>    setCopy(true);<br>    <em>setTimeout</em>(() =&gt; {<br>        setCopy(false);<br>    }, 1100);<br>}</pre><p>Bu metod ile ekranda çıkan kopyalama butonuna bastığımızda result state’indeki değeri CTRL+V yapabilmek için alıyoruz.</p><pre>const getResult = () =&gt; {<br>    setResult(null);<br>    setError(false);<br>    setLoading(true);<br>    <em>fetch</em>(&#39;generate&#39;, {<br>        method: &#39;POST&#39;,<br>        body: baseUrl<br>    }).then(res =&gt; res.text()).then(res =&gt; {<br>        const host = window.location.href;<br>        setResult(host + res);<br>        setLoading(false);<br>    }).catch(err =&gt; {<br>        setError(&#39;Error: Try again&#39;);<br>        setLoading(false);<br>    });<br>}</pre><p>Bu metod ile ise az önce spring boot ile yazmış olduğumuz servise istekte bulunuyoruz. Eğer istek başarılı olursa dönen sonucu ekranda göstermek üzere result state’ine aktarıyoruz başarısız olursa error state’ini setliyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac65dda49c4013221cb6b8fab692bd59/href">https://medium.com/media/ac65dda49c4013221cb6b8fab692bd59/href</a></iframe><p>Daha sonra yukarıdaki kodu fonksiyondan return ediyoruz. Burada kısaca açıklamak gerekirse bir tane material-ui’ın sağlamış olduğu TextField componentimiz var ve bu componente yazdığımız url baseUrl state’ine setleniyor. Bir tane içeriği Get URL olan butonumuz var ve bu butona basıldığında baseUrl state’iyle birlikte spring boot servisimize istek atıyor ve sonucu getiriyor. Loading state’i eğer true olur ise loading iconu ekranda görünüyor aynı şekilde error state’i içinde geçerli null veya false olmadıkça bu değerleri ekranda görebiliyoruz. En sonda ise result state’i null olmadığı durumlarda bir tane değiştirilemez TextField componenti içinde servisten dönen cevabı göstermiş oluyoruz. Hemen yanında IconButton componenti ile eğer servisten dönen değerin kopyalanması isteniyorsa kopyalayabilmesini sağlıyoruz. IconButton’un onClick eventinde yukarıda yazmış olduğumz copyUrl fonksiyonun çağrımını sağladık.</p><pre>import <em>makeStyles </em>from &quot;@material-ui/core/styles/makeStyles&quot;;<br><br>const useStyles = <em>makeStyles</em>({<br>    root: {<br>        display: &#39;grid&#39;,<br>        gridTemplateColumns: &#39;1fr auto&#39;,<br>        gap: &#39;8px&#39;<br>    },<br>    result: {<br>        width: &#39;100%&#39;,<br>        padding: &#39;20px&#39;,<br>        boxSizing: &#39;border-box&#39;<br>    },<br>    container: {<br>        position: &#39;relative&#39;<br>    },<br>    iconButton: {<br>        position: &#39;absolute&#39;,<br>        bottom: 0,<br>        right: 0,<br>        marginBottom: &#39;12px&#39;,<br>        marginRight: &#39;4px&#39;<br>    },<br>    loading: {<br>        display: &#39;flex&#39;,<br>        justifyContent: &#39;center&#39;,<br>        alignItems: &#39;center&#39;<br>    }<br>});<br><br>export default useStyles;</pre><p>url-shortener.styles.js dosyasına yukarıdaki stillerimizi yazıyoruz. Bununla birlikte aslında projemizin kodlama kısmı bitmiş oluyor.</p><h4>Reverse Proxy</h4><p>Nginx kullanarak projemizin frontend ve backend kodlarını aynı alan adı altında tutmaya çalışacağız ve frontend’den backend’e proxy aracılığıyla istek atacağız. Nginx kullanırken ise nginx docker imageları vasıtasıyla bu işlemi yapacağız. Öncelikle proje solution klasörümüzün içine nginx adında bir klasör oluşturalım ve <strong>nginx.conf </strong>adında bir dosya oluşturalım. Dosyanın içine aşağıdaki ayarları oluşturalım.</p><pre>server {<br>    listen 80<em>;<br></em>    server_name 0.0.0.0<em>;<br></em>    location /404 {<br>        proxy_pass http://frontend:3000/404/<em>;<br></em>    }<br><br>    location ~ &quot;^/([0-9a-zA-Z]{4,8})$&quot; {<br>        resolver 127.0.0.11<em>;<br></em>        proxy_pass http://app:6060/urlshortener/$1<em>;<br></em>    }<br>     location / {<br>        proxy_pass http://frontend:3000/<em>;<br></em>    }<br>    <br>}</pre><p>Burada 80 portunda ve 0.0.0.0 server_name’i olarak uygulamamızı açmak istediğimizi belirtiyoruz. Ardından location /404 ile server’imiza gelen alanadimiz.com/404 gibi bir isteğin frontend uygulamamizdaki 404 sayfasına yönlendirme yapmasını istiyoruz. Daha sonra bir altındaki location ile alfabe harfleri ve 0 dan 9 a kadar olan rakamları içeren ve 4 ile 8 karakter sayısında olan gelen istekleri backend uygulamamıza yönlendiriyoruz. Örneğin alanadimiz.com/generate şeklinde bir istek aldığımızda backend uygulamamiza bu isteğin gitmesini sağlamış oluyoruz. Ardından yine location / satırı ile sadece alanadimiz.com/ gibi bir istek gelirse bu isteği frontend uygulamamiza yönlendirmesini sağlamış oluyoruz böylece uygulamamız bir reverse proxy arkasında çalışmaya başlamış oluyor.</p><h4>Deploy edelim</h4><p>Birlikte örnek bir deploy yapmak için <a href="https://labs.play-with-docker.com/">Play With Docker</a> sitesini kullanacağız bu site bize 4&#39;er saatlik ve sınırlı kaynaklar (genelde işimizi görüyor) vererek docker öğrenme ve demo yapabilmemizi sağlıyor.</p><p>Öncelikle projemizi frontend, link-shortener ve nginx klasörleri olacak şekilde bir klasör altında toplayalım.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*w8euZjdbP79NOO4xYjMKvQ.png" /></figure><p>Klasör altında topladıktan sonra frontend klasörü içinde aşağıdaki Dockerfile’ı oluşturalım.</p><pre><em><br></em>FROM node:13.12.0-alpine<br><br><em><br></em>WORKDIR /app<br><br><em><br></em>ENV <em>PATH </em>/app/node_modules/.bin:$<em>PATH<br><br><br></em>COPY package.json ./<br>COPY package-lock.json ./<br>RUN npm install<br><br><em><br></em>COPY . ./<br><br><em><br></em>CMD [&quot;npm&quot;, &quot;start&quot;]</pre><p>Kısaca anlatmak gerekirse dosyalarımızı docker’a kopyalıyoruz ve npm install yaparak bağımlılıkları yüklemesini sağlıyoruz ardından npm start yaparak 3000 portunda çalışmasını sağlıyoruz. Daha sonra yine link-shortener klasörü altında Dockerfile oluşturuyoruz.</p><pre>FROM maven:3.5.2-jdk-8-alpine AS <em>MAVEN_BUILD<br><br></em>COPY pom.xml /build/<br>COPY src /build/src/<br><br>WORKDIR /build/<br>RUN mvn clean package spring-boot:repackage<br><br>FROM openjdk:8-jre-alpine<br><br>WORKDIR /app<br><br>COPY --from=<em>MAVEN_BUILD </em>/build/target /app/<br><br>EXPOSE 6060<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;urlshortener-0.0.1.jar&quot;]</pre><p>Burada ilk başta pom xml dosyamızı build klasörüne taşıyoruz ve ardından src klasörümüzü build/src altına taşıyoruz çalışma alanımızı build dizini olarak ayarladıktan sonra mvn clean package spring-boot:repackage komutunun çalıştırılmasını sağlıyoruz sonra alt satırlarda buradan çıkan jar dosyasının çalıştırılmasını sağlıyoruz. Docker bütün bu işlemleri bizim yerimize yapacaktır.</p><pre>FROM nginx:1.17.4-alpine<br><br>RUN rm /etc/nginx/conf.d/default.conf<br>COPY ./nginx.conf /etc/nginx/conf.d<br><br>EXPOSE 80<br>CMD [&quot;nginx&quot;, &quot;-g&quot;, &quot;daemon off;&quot;]</pre><p>Servis ve frontend dockerfile’larında olduğu gibi nginx içinde nginx klasörü altında dockerfile’imizi yukarıdaki gibi yazıyoruz. Daha sonra ana klasörümüzün içinde docker-compose.yaml adında bir dosya oluşturuyoruz ve içeriğini aşağıdaki gibi dolduruyoruz.</p><pre>version: &#39;3&#39;<br>services:<br>  nginx:<br>    build:<br>      context: nginx<br>      dockerfile: Dockerfile<br>    ports:<br>      - &#39;80:80&#39;<br>    restart: always<br>    expose:<br>      - &quot;80&quot;<br>    links:<br>      - &#39;app:app&#39;<br>      - &#39;frontend:frontend&#39;<br>  app:<br>    build:<br>      context: link-shortener<br>      dockerfile: Dockerfile<br>    restart: &#39;on-failure:10&#39;<br>    environment:<br>      MONGODB_URI: &lt;your-connection-string&gt;<br>  frontend:<br>    build:<br>      context: frontend<br>      dockerfile: Dockerfile<br>    restart: &#39;on-failure:10&#39;</pre><p>Docker Compose dosyamızda sırasıyla servislerimizi yazıyoruz. Nginx servisi içinde 80 portunu dışarıya yine 80 portuyla açacağımızı belirtiyoruz. Ardından app ve frontend uygulamalarına uygulamamızı bağlıyoruz. Uygulamamızın nginx klasörü altındaki Dockerfile ile ayağa kalkmasını belirttikten sonra aynı şekilde app ve frontend servislerini de yazıyoruz. App servisinde diğerlerinden farklı olarak environment MONGODB_URI environmentini setliyoruz. Daha sonra spring boot uygulamasında resources/application.yml altında aşağıdaki değişikliği yapıyoruz.</p><pre><strong>spring</strong>:<br>  <strong>data</strong>:<br>    <strong>mongodb</strong>:<br>      <strong>uri</strong>: ${<strong>MONGODB_URI</strong>}</pre><p>Bu değişiklikleride yaptıktan sonra uygulamamız docker-compose ile birlikte çalışabilir hale gelecektir.</p><p>Kodların tamamına <a href="https://github.com/nekinci/url-shortener">bu link</a> üzerinden erişebilirsiniz.</p><p>Dockerfile’larımızı da yazdığımıza göre;</p><ul><li><a href="https://labs.play-with-docker.com/">Play With Docker</a> adresine girerek giriş yapıyoruz.</li><li>Giriş yaptıktan sonra ‘Start’ butonuna basıyoruz.</li><li>Karşımıza gelen ekranda sol taraftan Add New Instance butonuna basıyoruz.</li><li>Makinamız oluştuktan sonra karşımızda terminal ekranı görüntülenecektir. Burada aşağıdaki komutu çalıştırarak projeyi instance’a indiriyoruz.</li></ul><pre>git clone https://github.com/nekinci/url-shortener.git</pre><p>Ardından aşağıdaki komutu çalıştırıyoruz,</p><pre>cd url-shortener</pre><p>Ve son olarak;</p><pre>docker-compose up</pre><p>Build tamamlandıktan sonra sayfanın üst kısmında 80 yazılı bir link çıkacaktır bu linke tıklayarak projeyi çalıştırabilirsiniz. Bilgisayarınızda docker yüklü ise aynı işlemleri yaparak bilgisayarınızda da test edebilirsiniz. Play With Docker’ın bize vermiş olduğu link tabii ki uzun olacaktır ama uygulamayı daha kısa bir domain adıyla deploy ettiğimizde amacına tam anlamıyla hizmet edecektir.</p><p>Projenin çalışır haliyle ilgili bir link bırakmak gerekirse;</p><p><a href="http://www.niceurl.live/1l7n97">niceurl.live/1l7n97</a> bu domain ile çalışırlığını test edebilirsiniz. Yine <a href="http://www.niceurl.live/">niceurl.live</a> adresine giderek URL kısaltabilirsiniz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf327368e2f7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Neden Repository Pattern kullanmalıyız?]]></title>
            <link>https://niyaziekinci.medium.com/neden-repository-pattern-kullanmal%C4%B1y%C4%B1z-bc25a166ddae?source=rss-5f121ac2a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc25a166ddae</guid>
            <category><![CDATA[net-core]]></category>
            <category><![CDATA[repository-pattern]]></category>
            <category><![CDATA[nhibernate]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[Niyazi Ekinci]]></dc:creator>
            <pubDate>Sat, 09 May 2020 13:40:51 GMT</pubDate>
            <atom:updated>2020-05-09T13:56:12.671Z</atom:updated>
            <content:encoded><![CDATA[<p>Herkese merhaba,</p><p>Şu sıralar bitirme projemle ilgilenmekteyim. Bitirme projemle uğraşırken bir çok şey öğrendim. Yanlış bildiğim bir çok şeyi düzeltme şansı elde ettim benim açımdan gayet verimli bir süreç oldu. Yine <strong>Repository Pattern</strong> ile de bu süreçte tanıştım. Yaşadığım süreçten kısaca bahsetmek istiyorum.</p><p>Öncelikle bitirme projemi yazarken endüstri standartlarında bir kod yazmak, temiz ve maintain edilebilir bir kod yazmak için arayış içindeydim. Çeşitli araştırmalar yaptım. Bu araştırmalar sonucu, bir çok mimariyle ve design pattern’le tanıştım. Repository Pattern ile de bu süreçte tanıştığımı belirtmiştim. Ne işe yaradığını ne amaçla kullanıldığını merak ederek tekrardan repository pattern ile ilgili araştırmalar yapmaya başladım. Araştırma yaparken, endüstri de yoğun bir şekilde tartışılan konuya rastladım. Tartışmanın konusu: <strong>Repository Pattern kullanmaya gerek var mı?</strong></p><p>Tartışma içinde, Entity Frameworkün zaten repository pattern kullanılarak yazıldığını, neden repository pattern kullanılarak yazılmış bir şeyi tekrardan repository pattern kullanarak yazmamız gerektiğini sorgulayan insanlar vardı. Bu soru, bana çok mantıklı gelmişti. Gerçekten Entity Frameworkun yapısına baktığımda Unit Of Work Pattern ile birlikte Repository Pattern kullanılmıştı. Ama tutorial’lara baktığımda ısrarla entity framework ile repository pattern’in birlikte kullanıldığını görmüştüm. Yine kullandığım framework gereği Microsoftun sitesindeki makaleleri okumaya başladım. Makalede Entity Framework’un zaten Repository Pattern kullanılarak yazıldığını ama isterseniz yine de bu patterni tekrar kullanabileceğiniz yazıyordu.</p><p>Daha sonra, soyutlama ve dependency injection ile tanıştım. Bu konu aslında soru işaretlerimi ortadan kaldırmaya yetmişti. Çünkü, Entity Frameworkun Repository Pattern kullanarak projeyi Databaseden soyutladığı gibi, Entity Frameworkün üzerine getirilen ek soyutlama(Repository Pattern) beni Entity Frameworkten soyutlayacaktı. Yani, nasıl ki, entity framework’te MySQL’den SQL Servera geçtiğimizde kodumuzda hiçbir değişiklik yapmıyorsak. Entity Framework’ten Dapper’a NHibernate’e geçtiğimizde üst katmanımızın hiç birşeyden haberi olmayacak ve üst katmanda hiç bir değişiklik yapmak zorunda kalmayacaktık. Üst katmanın bilmesi gereken sadece Data Access Layerla arasındaki olan sözleşme yani <strong>interface. </strong>Dependency Injection sayesinde, örneğin, IProductRepository Interface’imize dilediğimizde EfProductRepository’yi dilediğimizde HibernateProductRepository vererek üst katmanda hiçbir değişiklik yapmadan alt katmandaki frameworkü değiştirebileceğiz. Yine aynı şekilde veriye erişim katmanının test edilmesi kolaylaşacak. Aşağıda da görüldüğü gibi, EfProductRepository ve HibernateProductRepository IProductRepository interface’inden implement edilmiş ve üst katman olan ProductService dependency olarak IProductRepository’i almıştır. Yani ProductService sadece alt katmandan Productu alabildiğini, ekleyebildiğini bilmekte fakat bunun nasıl yapıldığını hangi database’e, hangi frameworkle erişildiğini bilmemekte. buda onu alt katmandan soyutlayarak daha az bağımlı olmasını sağlamaktadır. Yapılan herhangi bir değişiklik ProductService classını etkilemeyecektir.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e61152030428552ded07878b7fc210c0/href">https://medium.com/media/e61152030428552ded07878b7fc210c0/href</a></iframe><p>Yukarıdaki kod sadece IProductRepository interfaceine bağımlıdır. Startup.cs dosyasında IProductRepository’e concrete etmek istediğimiz classı (örneğimizde Hibernate veya Ef) vererek,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29c74aef3b04ec4fb08fe6f7b44c9368/href">https://medium.com/media/29c74aef3b04ec4fb08fe6f7b44c9368/href</a></iframe><p>ProductService class’ının yaratılma esnasında, IProductRepository yerine startup classına verdiğimiz classı oluşturması beklenmekte ve sonucunda kodumuz alt katmana daha az bağımlı olmaktadır.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5649b080a614c4e36f760dc932c2c27c/href">https://medium.com/media/5649b080a614c4e36f760dc932c2c27c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da0039bfd81e2376c1645d02b674f625/href">https://medium.com/media/da0039bfd81e2376c1645d02b674f625/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42aa5a798768d16dc609d7573f637896/href">https://medium.com/media/42aa5a798768d16dc609d7573f637896/href</a></iframe><p>Peki eğer Repository Pattern kullanmadan yani soyutlamadan, Product Service classını direkt olarak entity framework veya hibernate ile kodlarsak ne olurdu?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ea4fdc6f19b3f3a59279be6e009034f/href">https://medium.com/media/7ea4fdc6f19b3f3a59279be6e009034f/href</a></iframe><p>Gördüğümüz gibi Service classımız direkt olarak EntityFramework ile bağımlı eğer Hibernate’e geçmek istersem, ya service classındaki çoğu kodu (logic ile birlikte) yada direkt service classını değiştirmek zorunda kalacağım. Bu da hiç kimsenin, özellikle büyük projelerde, istemeyeceği birşeydir. Kısaca repository patternin aslında ne amaçla kullanıldığına ne işe yaradığına ve faydalarına değindik.</p><p>Umarım herkes için faydalı bir yazı olmuştur. Görüşmek üzere.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc25a166ddae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Client-Server & Pub-Sub Mimarileri]]></title>
            <link>https://niyaziekinci.medium.com/client-server-pub-sub-mimarileri-2c5e09362962?source=rss-5f121ac2a598------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c5e09362962</guid>
            <category><![CDATA[network]]></category>
            <category><![CDATA[servers]]></category>
            <category><![CDATA[sub]]></category>
            <category><![CDATA[clients]]></category>
            <category><![CDATA[pub]]></category>
            <dc:creator><![CDATA[Niyazi Ekinci]]></dc:creator>
            <pubDate>Sun, 08 Dec 2019 08:16:40 GMT</pubDate>
            <atom:updated>2019-12-08T08:16:40.109Z</atom:updated>
            <content:encoded><![CDATA[<p>Herkese merhaba arkadaşlar,<br>Bugün sizlerle <strong>client-server ve pub-sub mimarilerine</strong> kısaca değineceğiz.</p><p>Bilgisayar ağlarında günümüzde ve geçmişte sıkça kullanılan patternler arasında hiç şüphesiz client-server mimarisi ilk sıradadır. Client-Server mimarisiyle, sunucu(server) istemci(client) bilgisayarlara istenen içeriği vermektedir.</p><p>Client-Server mimarisinde, istemci bir istekte bulunmadan sunucu cevap veremez. İstemci istekte bulunduktan sonra boşta olan sunucu bilgisayarlardan biri istemciye istediği içeriği vermektedir. Web sitesi üzerinden örnek verecek olursak, bir web sitesinin bir sayfasını görüntülemeye çalıştığımızda önce sunucuya bir istekte bulunmamız gerekir ardından sunucu bize görmek istediğimiz sayfanın içeriğini gönderir ve görmemizi sağlar. Yine bir web sitesinin, olmayan bir sayfasını görüntülemeye çalıştığımızda sunucu, istemciye 404 mesajı göndererek bir cevap döndürecektir. <br><strong>Kısaca</strong>, Client-Server mimarisinde, istemci istekte bulunduktan sonra sunucu cevap vermektedir. Mimari bunun üzerine kuruludur ve yaşam döngüsü istekler-cevaplar üzerinedir.</p><p>Pub-Sub mimarisi ise, <strong>Publisher(Yayıncı), </strong>bir kanal açarak veriyi o kanaldan aktarmaya başlar, kimsenin bir istekte bulunmasına gerek yoktur. <strong>Subscriber(Abone) </strong>ise yayıncının veriyi aktardığı kanala abone olarak veriyi alır ve istediği şekilde işler. Yani publisher’ın subscriberlardan haberi bile yoktur. Client-Server’da server bütün clientlardan haberdardı. Subscriberlar ise sadece kanala üye olurlar ve oradan gelen veriyle ilgilenirler, publisheri bilmezler sadece kanala üye olmaları yeterlidir.<br>Örnek olarak, Pub-Sub ile çalışan canlı yayın uygulaması yaptığımızı düşünelim. Canlı yayın yaptığımız kaynağı publisher yaparak, kanala anlık olarak veriyi verebiliriz ardından subscriber ile ilgili kanala üye olarak veriyi canlı olarak alabiliriz.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c5e09362962" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>