Spring Boot ve Redis Önbellek Kullanarak Müşteri Verilerini Hızlandırma: Adım Adım Rehber

 İşte müşteri bilgilerini Redis cache'de tutan basit bir Spring Boot uygulamasının örnek senaryosu ve kodları:



### Gereksinimler


- Spring Boot

- Spring Data JPA

- Spring Data Redis

- H2 Database (veya herhangi bir veritabanı)

- Redis Server


### 1. Proje Yapılandırması


#### `pom.xml` veya `build.gradle`


```xml

<dependencies>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-data-jpa</artifactId>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-data-redis</artifactId>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-web</artifactId>

    </dependency>

    <dependency>

        <groupId>com.h2database</groupId>

        <artifactId>h2</artifactId>

        <scope>runtime</scope>

    </dependency>

    <dependency>

        <groupId>org.springframework.boot</groupId>

        <artifactId>spring-boot-starter-test</artifactId>

        <scope>test</scope>

    </dependency>

</dependencies>

```


### 2. Redis ve JPA Yapılandırması


#### `application.properties`


```properties

# H2 Database Configuration

spring.datasource.url=jdbc:h2:mem:testdb

spring.datasource.driverClassName=org.h2.Driver

spring.datasource.username=sa

spring.datasource.password=password

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

spring.h2.console.enabled=true


# Redis Configuration

spring.redis.host=localhost

spring.redis.port=6379

```


### 3. Entity Sınıfı


#### `Customer.java`


```java

import javax.persistence.Entity;

import javax.persistence.GeneratedValue;

import javax.persistence.GenerationType;

import javax.persistence.Id;

import java.io.Serializable;


@Entity

public class Customer implements Serializable {


    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    private String name;

    private String email;


    // Getters and Setters

}

```


### 4. Repository


#### `CustomerRepository.java`


```java

import org.springframework.data.jpa.repository.JpaRepository;


public interface CustomerRepository extends JpaRepository<Customer, Long> {

}

```


### 5. Service Sınıfı


#### `CustomerService.java`


```java

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.cache.annotation.Cacheable;

import org.springframework.stereotype.Service;


import java.util.Optional;


@Service

public class CustomerService {


    @Autowired

    private CustomerRepository customerRepository;


    @Cacheable(value = "customerCache", key = "#id")

    public Optional<Customer> getCustomerById(Long id) {

        return customerRepository.findById(id);

    }

}

```


### 6. Controller


#### `CustomerController.java`


```java

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RestController;


import java.util.Optional;


@RestController

public class CustomerController {


    @Autowired

    private CustomerService customerService;


    @GetMapping("/customers/{id}")

    public Optional<Customer> getCustomer(@PathVariable Long id) {

        return customerService.getCustomerById(id);

    }

}

```


### 7. Redis Cache Yapılandırması


#### `RedisConfig.java`


```java

import org.springframework.cache.annotation.EnableCaching;

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.data.redis.cache.RedisCacheConfiguration;

import org.springframework.data.redis.cache.RedisCacheManager;

import org.springframework.data.redis.connection.RedisConnectionFactory;

import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import org.springframework.data.redis.serializer.StringRedisSerializer;


import java.time.Duration;


@Configuration

@EnableCaching

public class RedisConfig {


    @Bean

    public RedisConnectionFactory redisConnectionFactory() {

        return new LettuceConnectionFactory();

    }


    @Bean

    public RedisTemplate<String, Object> redisTemplate() {

        RedisTemplate<String, Object> template = new RedisTemplate<>();

        template.setConnectionFactory(redisConnectionFactory());

        template.setKeySerializer(new StringRedisSerializer());

        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        return template;

    }


    @Bean

    public RedisCacheManager cacheManager() {

        RedisCacheConfiguration cacheConfig = RedisCacheConfiguration.defaultCacheConfig()

                .entryTtl(Duration.ofMinutes(10))

                .disableCachingNullValues();


        return RedisCacheManager.builder(redisConnectionFactory())

                .cacheDefaults(cacheConfig)

                .build();

    }

}

```


### 8. Ana Uygulama Sınıfı


#### `Application.java`


```java

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;


@SpringBootApplication

public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);

    }

}

```


Bu örnek ile müşteri bilgilerini Redis cache'de tutan basit bir Spring Boot uygulaması oluşturabilirsiniz. Uygulama çalıştığında, `/customers/{id}` endpoint'ine yapılan isteklerde müşteri bilgileri önce Redis cache'den kontrol edilecek, eğer cache'de bulunmazsa veritabanından alınacak ve cache'e kaydedilecektir.

Please Select Embedded Mode To Show The Comment System.*

Daha yeni Daha eski

نموذج الاتصال