SpringCache etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
SpringCache etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

3 Mayıs 2023 Çarşamba

SpringCache CachingConfigurerSupport Sınıfı

Giriş
Şu satırı dahil ederiz.
import org.springframework.cache.annotation.CachingConfigurerSupport;
Birden fazla Cache kullanacaksan bir tanesini @Primary olarak işaretlemeye gerek kalmaz. cacheManager() tarafından döndürülen nesne @Primary kabul edilir. Şöyle yaparız
@Configuration
@EnableCaching
public class MultipleCacheManagerConfig extends CachingConfigurerSupport {

  @Bean
  public CacheManager cacheManager() {
    CaffeineCacheManager cacheManager = new CaffeineCacheManager("customers", "orders");
    cacheManager.setCaffeine(Caffeine.newBuilder()
      .initialCapacity(200)
      .maximumSize(500)
      .weakKeys()
      .recordStats());
    return cacheManager;
  }

  @Bean
  public CacheManager alternateCacheManager() {
    return new ConcurrentMapCacheManager("customerOrders", "orderprice");
  }
}


14 Nisan 2023 Cuma

SpringCache SimpleCacheManager Sınıfı

Giriş
Şu satırı dahil ederiz
import  org.springframework.cache.support.SimpleCacheManager;
Örnek
Şöyle yaparız
@Configuration
@EnableCaching
public class CachingConfig {

  @Bean
  public CacheManager cacheManager() {
    SimpleCacheManager cacheManager = new SimpleCacheManager();
    cacheManager.setCaches(Arrays.asList(
      new ConcurrentMapCache("directory"), 
      new ConcurrentMapCache("addresses")));
    return cacheManager;
  }
}
Örnek
Şöyle yaparız.
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
  <property name="caches">
    <set>
      <bean class="org.springframework.cache.concurrent.ConcurrentMapCacheFactoryBean"
         p:name="foo"/>
    </set>
  </property>
</bean>

6 Şubat 2023 Pazartesi

SpringCache CompositeCacheManager Sınıfı

Örnek
Şöyle yaparız
@Configuration
class MyCachingConfiguration {

  @Bean
  RedisCacheManager cacheManager() {
    // ...
  }

  @Bean
  HazelcastCacheManager hazelcastCacheManager() {
    // ...
  }

  @Bean
  CompositeCacheManager compositeCacheManager(RedisCacheManager redis, 
    HazelcastCacheManager hazelcast) {
    return new CompositeCacheManager(redis, hazelcast);
  }
}

30 Ocak 2023 Pazartesi

SpringCache CacheErrorHandler - Redis Server Inaccessibility Yani Redis Erişimindeki Hatalar İçindir


Giriş
Şu satırı dahil ederiz 
import org.springframework.cache.interceptor.CacheErrorHandler;
Açıklaması şöyle
We define a custom error handler to handle any exceptions occurred during any Redis command execution. This helps to connect to the actual source of data instead of throwing an exception if the Redis command execution failed.
CachingConfigurer arayüzünü gerçekleştiren sınıfımızın errorHandler() metodunu override etmek gerekir

Örnek
Şöyle yaparız
@Override
public CacheErrorHandler errorHandler() {
  return new CacheErrorHandler() {
   @Override
   public void handleCacheGetError(RuntimeException exception, Cache cache, 
     Object key) {
   }

   @Override
   public void handleCachePutError(RuntimeException exception, Cache cache, 
    Object key, Object value) {
   }

    @Override
    public void handleCacheEvictError(RuntimeException exception, Cache cache,
      Object key) {
    }

    @Override
    public void handleCacheClearError(RuntimeException exception, Cache cache) {
    }
  };
}
Örnek
Şöyle yaparız
import org.springframework.cache.annotation.CachingConfigurer;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.context.annotation.Configuration;

@Configuration
public class CachingConfiguration implements CachingConfigurer {

  @Override
  public CacheErrorHandler errorHandler() {
    return new CustomCacheErrorHandler();
  }
}

import org.springframework.cache.interceptor.CacheErrorHandler;

public class CustomCacheErrorHandler implements CacheErrorHandler {

  @Override
  public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
  }

  @Override
  public void handleCachePutError(RuntimeException exception, Cache cache, Object key,
    Object value) {
  }

  @Override
  public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
  }

  @Override
  public void handleCacheClearError(RuntimeException exception, Cache cache) {
  }
}



14 Ekim 2022 Cuma

SpringCache JCache Kullanımı

Giriş
Spring org.springframework.cache.jcache.JCacheCacheManager ile iletişime geçer. Bu sınıfta kendisine takılan ve JCache standardını gerçekleştiren herhangi bir kütüphaneyi kullanır. Açıklaması şöyle
JCache is bootstrapped through the presence of a javax.cache.spi.CachingProvider on the classpath (that is, a JSR-107 compliant caching library exists on the classpath),...
Açıklaması şöyle
JCache is the standard caching API for Java. It is provided by javax.cache.spi.CachingProvider.

It is present on the classpath. The spring-boot-starter-cache provides the JCacheCacheManager.
Maven
Şöyle yaparız. İlave olarak JCache Provider'ın dependency'si de eklenir
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
  <groupId>javax.cache</groupId>
  <artifactId>cache-api</artifactId>
</dependency>
Örnek - Hazelcast
Şöyle yaparız
debug=true
spring.cache.type=jcache
spring.cache.jcache.config=classpath:hazelcast.xml
spring.cache.jcache.provider=com.hazelcast.cache.impl.HazelcastServerCachingProvider
Örnek - Hazelcast
Şöyle yaparız
# Configure the cache
#spring.cache.jcache.provider=com.hazelcast.client.cache.HazelcastClientCachingProvider
spring.cache.jcache.provider=com.hazelcast.cache.HazelcastMemberCachingProvider

Örnek - XML ile Hazelcast
Şöyle yaparız. Burada JCache Standardını gerçekleştiren org.springframework.cache.jcache.JCacheCacheManager nesnesine bir com.hazelcast.cache.HazelcastCacheManager nesnesi geçiliyor
<cache:annotation-driven cache-manager="cacheManager" />

<hz:hazelcast id="instance">
    ...
</hz:hazelcast>

<hz:cache-manager id="hazelcastJCacheCacheManager" instance-ref="instance" 
  name="hazelcastJCacheCacheManager"/>

<bean id="cacheManager" class="org.springframework.cache.jcache.JCacheCacheManager">
    <constructor-arg ref="hazelcastJCacheCacheManager" />
</bean>

SpringCache Couchbase

Giriş
Açıklaması şöyle
Couchbase is a NoSQL database that can act as cache provider on top of the spring boot cache abstraction layer.

The CouchbaseCacheManager is automatically configured when we implement couchbase-spring-cache and configure couchbase.
Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>com.couchbase.client</groupId>
  <artifactId>couchbase-spring-cache</artifactId>
</dependency>



23 Eylül 2022 Cuma

SpringCache Infinispan Kullanımı

Giriş
Açıklaması şöyle. Sanırım Hazelcast ile aynı işi görüyor. Yani hem embedded hem de data grid gibi kullanılabiliyor
Infinispan is an open-source in-memory data grid that offers flexible deployment options and robust capabilities for storing, managing, and processing data. Infinispan provides a key/value data store that can hold all types of data, from Java objects to plain text. Infinispan distributes your data across elastically scalable clusters to guarantee high availability and fault tolerance, whether you use Infinispan as a volatile cache or a persistent data store.
Bir örnek burada

Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>org.infinispan</groupId>
  <artifactId>infinispan-core</artifactId>
</dependency>
Örnek
Şöyle yaparız
spring.cache.infinispan.config=infinispan.xml




1 Eylül 2022 Perşembe

SpringCache application.properties Ayarları

Örnek - none
Cache işlevini kapatmak için şöyle yaparız.
spring.cache.type = none
Redis
SpringCache Redis Kullanımı yazısına taşıdım

11 Mayıs 2022 Çarşamba

SpringCache Caffeine

Giriş
Açıklaması şöyle
The spring boot automatically configures the CaffeineCacheManager if Caffeine is found in the classpath.
Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>com.github.ben-manes.caffeine</groupId>
  <artifactId>caffeine</artifactId>
</dependency>
Bir örnek burada

13 Aralık 2021 Pazartesi

SpringCache Ehcache 3 Kullanımı

Giriş
Açıklaması şöyle
The EhCache is an open source Java based cache used to boost performance. It stores the cache in memory and disk (SSD).

EhCache used a file called ehcache.xml. The EhCacheCacheManager is automatically configured if the application found the file on the classpath.
Maven
Şu satırı dahil ederiz
<dependency>
<groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> <version>3.9.6</version> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> <version>1.1.0</version> <scope>runtime</scope> </dependency>
Açıklaması şöyle
You need both JCache and EhCache if you are using EhCache v3. In the previous v2, JCache was not needed as it was not built upon the JSR standard.
Bundan sonra cache ayarlarını ya xml ya da kodla vermek gerekir.

XML İle Belirtmek
application.properties dosyasında şöyle yaparız
spring.cache.jcache.config=classpath:ehcache.xml
ehcache.xml
Örnek
Şöyle yaparız.
<config
  xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
  xmlns='http://www.ehcache.org/v3'
  xsi:schemaLocation="http://www.ehcache.org/v3
                      http://www.ehcache.org/schema/ehcache-core.xsd">

  <cache alias="cache_10s">
    <expiry>
      <ttl unit="seconds">10</ttl>
    </expiry>
    <heap unit="entries">10000</heap>
  </cache>

  <cache alias="cache_30s">
    <expiry>
      <ttl unit="seconds">30</ttl>
    </expiry>
    <heap unit="entries">10000</heap>
  </cache>
</config>
Örnek
Şöyle yaparız. Burada offheap ile JVM dışında kulanılabilecek bellek belirtiliyor.
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns="http://www.ehcache.org/v3"
   xmlns:jsr107="http://www.ehcache.org/v3/jsr107"
   xsi:schemaLocation="
     http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd
     http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd">

  <cache alias="allUserCache">
    <key-type>java.lang.String</key-type>
    <value-type>java.util.List</value-type>
    <expiry>
      <ttl unit="seconds">30</ttl>
    </expiry>
    <resources>
      <heap unit="entries">10</heap>
      <offheap unit="MB">10</offheap>
    </resources>
  </cache>
</config>
Kodla Belirtmek
1. org.ehcache.config.builders.CacheManagerBuilder kullanılır
Ehcache 3 CacheManagerBuilder Sınıfı yazında Ehcache3 ayarları görülebilir.
JCacheCacheManager Sınıfı - EhCache 3 yazında Ehcache3 ile Spring'in nasıl birleştirildiği görülebilir.

2. Eh107Configuration kullanılır
Örnek
Şöyle yaparız. Burada  org.ehcache.config.builders.CacheManagerBuilder kullanılarak bir org.ehcache.config.CacheConfiguration yaratılıyor. 

Daha sonra org.ehcache.jsr107.Eh107Configuration kullanılarak CacheConfiguration nesnesi 
JSR-107 javax.cache.configuration.Configuration haline çevriliyor.
Daha sonra JSR-107 configuration nesnesi yine JSR-107 javax.cache.spi.CachingProvider nesnesine takılıyor
import org.ehcache.config.CacheConfiguration;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ExpiryPolicyBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.jsr107.Eh107Configuration;
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.spi.CachingProvider;
import java.time.Duration;

@Configuration
public class AppConfig {

  @Bean
  public CacheManager EhcacheManager() {

    CacheConfiguration<String, Person> cachecConfig = CacheConfigurationBuilder
      .newCacheConfigurationBuilder(String.class,
                        Person.class,
                        ResourcePoolsBuilder.newResourcePoolsBuilder()
                                .offheap(10, MemoryUnit.MB)
                                .build())
      .withExpiry(ExpiryPolicyBuilder.timeToIdleExpiration(Duration.ofSeconds(10)))
      .build();

    CachingProvider cachingProvider = Caching.getCachingProvider();
    CacheManager cacheManager = cachingProvider.getCacheManager();

    javax.cache.configuration.Configuration<String, Person> configuration = Eh107Configuration.fromEhcacheCacheConfiguration(cachecConfig);
    cacheManager.createCache("cacheStore", configuration);
    return cacheManager;
  }
}

5 Ağustos 2021 Perşembe

SpringCache @Caching Anotasyonu

Açıklaması şöyle
@Caching : Regroups multiple cache operations to be applied on a method
evict Alanı
Açıklaması şöyle
@Caching: Java doesn’t allow you to use the same annotation type twice in a method or class. So, if you want to say @CacheEvict in two different caches in the same method @Cacheable can be used to aggregate other cache annotations.
Örnek
Şöyle yaparız
@Caching(evict = {
  @CacheEvict(“address”), 
  @CacheEvict(value=“employee”, key=”#employee.id”)
})
public Employee getEmployee(Employee employee) {
  // some code
}
Örnek
Şöyle yaparız. Burada aynı anda iki cache'ten birden silme işlemi olduğu için @Caching kullanılıyor
@RestController("/")
public class TodoListController {

  private ToDoList sample = new ToDoList(1, new ArrayList<ToDo>(Arrays.asList(
new ToDo(1, "Comment", false), 
    new ToDo(2, "Clap", false),
    new ToDo(3, "Follow Author", false))), false);

  @DeleteMapping("/todo/{id}")
  @Caching(evict = {
    @CacheEvict(value = "todo-single", key = "#id"),
    @CacheEvict(value="todo-list", key="'getList'")
  })
  public void deleteToDo(@PathVariable("id") long id) throws Exception {
    Optional<ToDo> item = sample.getTasks().stream()
.filter(x -> x.getId() == id).findFirst();
    if (item.isPresent()) {
      sample.getTasks().remove(item.get());
    } else {
      throw new Exception("To Do item not found");
    }
  }
}
Geri kalan kodları şöyle yaparız
@Cacheable(value = "todo-list" , key="'getList'")
@GetMapping
public ToDoList getList() {
  return sample;
}

@Cacheable(value = "todo-single", key = "#id")
@GetMapping("/todo/{id}")
public Optional<ToDo> getToDo(@PathVariable("id") long id) {
  return sample.getTasks().stream().filter(x -> x.getId() == id).findFirst();
}

@PutMapping("/todo")
@CachePut(value = "todo-single", key = "#toDo.id")
@CacheEvict(value="todo-list" , key="'getList'")
public ToDoList addToDo(@RequestBody ToDo toDo) {
  sample.getTasks().add(toDo);
  return sample;
}

@PostMapping("/todo/{id}")
@CachePut(value = "todo-single", key = "#id")
@CacheEvict(value="todo-list", key="'getList'")
public ToDo updateToDo(@PathVariable("id") long id, @RequestBody ToDo toDo)
throws Exception {
  Optional<ToDo> item = sample.getTasks().stream()
.filter(x -> x.getId() == id).findFirst();
  if (item.isPresent()) {
    item.get().setCompleted(toDo.isCompleted());
    return item.get();
  } else {
    throw new Exception("To Do item not found");
  }
}
Ve şöyle yaparız
@DeleteMapping("/todo/{id}")
@Caching(evict = {
@CacheEvict(value = "todo-single", key = "#id"),
  @CacheEvict(value="todo-list", key="'getList'")
})
public void deleteToDo(@PathVariable("id") long id) throws Exception {
  Optional<ToDo> item = sample.getTasks().stream()
.filter(x -> x.getId() == id).findFirst();
  if (item.isPresent()) {
    sample.getTasks().remove(item.get());
  } else {
    throw new Exception("To Do item not found");
  }
}

19 Temmuz 2021 Pazartesi

SpringCache Redis RedisCacheManagerBuilderCustomizer Sınıfı

Örnek
Şöyle yaparız
@Bean
public RedisCacheManagerBuilderCustomizer redisCacheManagerBuilderCustomizer() {
  return builder -> builder
    .withCacheConfiguration(“AccountCache",
      RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(60)))
    .withCacheConfiguration(“ProductCache",
      RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(120)));
}

6 Mayıs 2021 Perşembe

SpringCache @CacheConfig Anotasyonu

Giriş
Eğer nesnenin belli bir isme sahip cache alanına eklenmesini istersek @CacheConfig anotasyonu ile cache ismi belirtilir. Açıklaması şöyle
It is a class level annotation. It is used to share common properties such as cache name, cache manager to all methods annotated with cache annotations.

When a class is declared with this annotation then it provides default setting for any cache operation defined in that class. Using this annotation, we do need to declare things multiple times.
Örnek
Şöyle yaparız. Burada cache ismi her metod için geçerli
@Service
@CacheConfig(cacheNames=”employees”) public class EmployeeService { @Cacheable public Employee findById(int id) { // some code } }
Örnek
Şöyle yaparız
@Service
@CacheConfig(cacheNames = "customerCache")
public class CustomerService {

  @Cacheable(cacheNames = "customers")
  public List<Customer> getAll() {
    ...
  }
}

4 Mart 2021 Perşembe

SpringCache Kullanımı

Giriş
Kısaca 
1. @EnableCaching ile cache etkinleştirilir
2. Bir CacheManager Arayüzü tanımlanır
3. @Cacheable select, find metodları için kullanılır
4. @CachePut update metodları için kullanılır
5. @CacheEvict delete metodları için kullanılır
6. @Caching metod üzerinde birden fazla aynı cache anotasyonunu kullanmak birden fazla defa kullanmak istiyorsak bunları birleştirmek için kullanılır. Çünkü Java aynı anotasyonunu iki defa eklenmesine izin vermez. Örneğin bir metod çağrısında iki farklı cahce'ten bir şey silmek istiyorsak işe yarar
7. @CacheConfig sınıf üzerine yazılır. Sınıfta kullanılan tüm cache anotasyonlarına ortak özellikler verir

Bir başka açıklama şöyle
@Cacheable : Triggers cache population
@CachePut : Updates the cache, without interfering with the method execution
@CacheEvict : Triggers cache eviction[removing items from cache]
@Caching : Regroups multiple cache operations to be applied on a method
@CacheConfig : Shares some common cache-related settings at class-level
@EnableCaching : Configuration level annotation, enables Caching
Desteklenen Cache Sağlayıcıları
Açıklaması şöyle
The following are the cache provider supported by Spring Boot framework :

1. JCache (JSR-107)
2. EhCache
3. Hazelcast
4. Infinispan
5. Couchbase
6. Redis
7. Caffeine
8. Simple