17 Temmuz 2019 Çarşamba

SpringData Redis RedisTemplate Sınıfı

Giriş
Maven ile şu satırı dahil ederiz.
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Bu sınıfı elle yaratıyorsak
setDefaultSerializer 
setKeySerializer
setValueSerializer
setHashKeySerializer
setHashValueSerializer
metodlarını kullanarak serializer ayarlarını yapmak gerekiyor

constructor
Şöyle yaparız. Nesneyi yarattıktan sonra setConnectionFactory() metodunu çağırmak gerekir.
RedisTemplate<String, Object> template = new RedisTemplate<>();
enableTransaction metodu
Şöyle yaparız
@Bean
public RedisTemplate<String, Object> redisTemplate() {
  RedisTemplate redisTemplate = new RedisTemplate();
  redisTemplate.setConnectionFactory(redisConnectionFactory());
  redisTemplate.setKeySerializer(new StringRedisSerializer());
  redisTemplate.setValueSerializer(new StringRedisSerializer());
  redisTemplate.setEnableTransactionSupport(true);
  return redisTemplate;
}
execute metodu
Örnek
Şöyle yaparız.
template.execute(new SessionCallback<List<Object>>() {
 //...
});
Örnek
Şöyle yaparız.
template.execute(new RedisCallback<Void>() {
// ...
}
Örnek
Şöyle yaparız.. Burada redis ile transaction yapmanın iki yöntemi gösteriliyor. Birinci yöntemde  operations.multi(); ve operations.exec(); kullanılıyor. İkinci yöntemde @Transactional kullanılıyor
public void saveNumbersUsingTransaction() {
  redisTemplate.execute(new SessionCallback() {
    public void execute(RedisOperations operations) throws DataAccessException {
      operations.multi();
      try {
        StringBuilder redisValue = ...;
        operations.opsForValue().set("numbers", redisValue.toString());

        operations.exec();
      } catch (Exception e) {
        operations.discard();
      }
    }
  );
}

@Transactional
public void saveNumbersUsingTransactionWithAnnotation() {
  redisTemplate.execute(new SessionCallback() {
    public void execute(RedisOperations operations) throws DataAccessException {
      operations.multi();

      StringBuilder redisValue = ...;
      operations.opsForValue().set("numbersAsText", redisValue.toString());

    }
  });
}
expire metodu
Verilen key nesnenin ne zaman silineceğini belirtir.
Örnek
Şöyle yaparız
String name = ...
redisTemplate.expire(name, 10, TimeUnit.SECONDS);
hasKey metodu
Örnek ver

opsForHash metodu
HashOperations nesnesi döner.

opsForHyperLogLog metodu
HyperLogLogOperations nesnesi döndürür.

opsForList metodu
ListOperations nesnesi döner

opsForSet metodu
SetOperations nesnesi döner

opsForValue metodu
ValueOperations nesnesi döner

setConnectionFactory metodu
Örnek - LettuceConnectionFactory 
Şöyle yaparız.
@Bean
public LettuceConnectionFactory getConnectionFactory(){
  LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(
    "localhost",6379);
  return lettuceConnectionFactory;
}

@Bean
public RedisTemplate<String,Object> getRedisTemplate(){
  RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
  redisTemplate.setConnectionFactory(getConnectionFactory());
  return redisTemplate;
}
Örnek - JedisConnectionFactory
Şöyle yaparız
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig" p:max-total="400" 
:maxIdle="350" p:maxWaitMillis="1000"
  p:test-on-borrow="true" p:test-on-return="true" p:testOnCreate="true" />

<bean id="jedisConnectionFactory"
 class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
     p:host-name="127.0.0.1" p:port="6379" p:use-pool="true" p:password="11223344">
   <constructor-arg ref="jedisPoolConfig"/>
</bean>

<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"
 p:connection-factory-ref="jedisConnectionFactory" p:enable-transaction-support="true"/>
Örnek - JedisConnectionFactory
Şöyle yaparız.
@Bean
JedisConnectionFactory jedisConnectionFactory() {
  JedisConnectionFactory jedisConFactory = new JedisConnectionFactory();
  jedisConFactory.setHostName("localhost");
  jedisConFactory.setPort(6379);
  return jedisConFactory;
}

@Bean
public RedisTemplate<String, Object> redisTemplate() {
  RedisTemplate<String, Object> template = new RedisTemplate<>();
  template.setConnectionFactory(jedisConnectionFactory());
  return template;
}
setDefaultSerializer metodu
Serializer olarak
- JdkSerializationRedisSerializer
- Jackson2JsonRedisSerializer
- GenericJackson2JsonRedisSerializer
kullanılabilir. Açıklaması şöyle
By default, RedisCache and RedisTemplate are configured to use Java native serialization.
Açıklaması şöyle
Data can be stored by using various data structures within Redis. Jackson2JsonRedisSerializer can convert objects in JSON format. Ideally, JSON can be stored as a value by using plain keys. You can achieve a more sophisticated mapping of structured objects by using Redis hashes. Spring Data Redis offers various strategies for mapping data to hashes (depending on the use case):
  • Direct mapping, by using HashOperations and a serializer
  • Using Redis Repositories
  • Using HashMapper and HashOperations
Varsayılan serializer JdkSerializationRedisSerializer sınıfıdır. Değiştirmek için şöyle yaparız.
 template.setDefaultSerializer(new StringRedisSerializer()); // set here
setHashKeySerializer metodu
GenericToStringSerializer verilir
Örnek
Şöyle yaparız
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    
  @Bean
  public RedisTemplate<String, Object> redisTemplate() {
    RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
    redisTemplate.setKeySerializer(new StringRedisSerializer());
    redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
    redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer());
    redisTemplate.setConnectionFactory(redisConnectionFactory());
    return redisTemplate;
  }
}
setHashValueSerializer metoud
JdkSerializationRedisSerializer,  Jackson2JsonRedisSerializer verilir
Örnek
Şöyle yaparız
@Value(value = "${spring.redis.cluster.nodes}") private String clusterNode; @Bean public JedisConnectionFactory jedisConnectionFactory() { return new JedisConnectionFactory(new RedisClusterConfiguration(List.of(clusterNode))); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(jedisConnectionFactory()); var objectMapper = createObjectMapper(); var jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; } private ObjectMapper createObjectMapper() { var objectMapper = new ObjectMapper(); ... return objectMapper; }
setKeySerializer metodu
StringRedisSerializer verilir
Örnek
Şöyle yaparız.
@Bean
public RedisTemplate<String, Object> redisTemplate(){
  Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = 
    new Jackson2JsonRedisSerializer(Object.class);

  final RedisTemplate<String, Object> template = new RedisTemplate<>();
  template.setConnectionFactory(jedisConnectionFactory());
  template.setKeySerializer(new StringRedisSerializer());
  template.setHashValueSerializer(jackson2JsonRedisSerializer);
  template.setValueSerializer(jackson2JsonRedisSerializer);
  return template;
}

Hiç yorum yok:

Yorum Gönder