25 Ocak 2021 Pazartesi

SpringData Redis ReactiveRedisTemplate Sınıfı

Giriş
Şu satırı dahil ederiz
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
Bu sınıf ReactiveRedisOperations'tan kalıtır
constructor
Şöyle yaparız
@Configuration
public class ReactiveRedisConfiguration {

  private final Environment env;

  public ReactiveRedisConfiguration(Environment env) {
    this.env = env;
  }

  @Bean
  public ReactiveRedisConnectionFactory reactiveRedisConnectionFactory() {
    return new LettuceConnectionFactory(
      Objects.requireNonNull(env.getProperty("spring.redis.host")),
      Integer.parseInt(Objects.requireNonNull(env.getProperty("spring.redis.port"))));
  }


  @Bean
  public ReactiveRedisOperations<String, Object> redisOperations(
    ReactiveRedisConnectionFactory reactiveRedisConnectionFactory) {
    Jackson2JsonRedisSerializer<Object> serializer = 
      new Jackson2JsonRedisSerializer<>(Object.class);

    RedisSerializationContext.RedisSerializationContextBuilder<String, Object> builder =
      RedisSerializationContext.newSerializationContext(new StringRedisSerializer());

    RedisSerializationContext<String, Object> context = builder.value(serializer)
      .hashValue(serializer)
      .hashKey(serializer).build();

    return new ReactiveRedisTemplate<>(reactiveRedisConnectionFactory, context);
  }
}
opsForHash metodu
Örnek
Şöyle yaparız
public Mono<Object> set(String key, String hashKey, Object val) {
  return redisOperations.opsForHash().put(key, hashKey, val).map(b -> val);
}

public Flux<Object> get(@NotNull String key){
  return redisOperations.opsForHash().values(key);
}

public Mono<Object> get(String key, Object hashKey) {
  return redisOperations.opsForHash().get(key, hashKey);
}

public Mono<Long> remove(String key, Object hashKey) {
  return redisOperations.opsForHash().remove(key, hashKey);
}

opsForStream metodu
Redis Streams kullanabilmeyi sağlar

Örnek
Mesaj publish etmek için şöyle yaparız
String streamKey = "movie-events"
MovieDetails movieDetails = ...
ObjectRecord<String, MovieDetails> record = StreamRecords.newRecord()
  .ofObject(movieDetails)
  .withStreamKey(streamKey);

redisTemplate
  .opsForStream()
  .add(record)
  .subscribe(System.out::println);
Mesajı almak için şöyle yaparız
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.stream.StreamListener;

public class MovieEventConsumer implements
StreamListener<String, ObjectRecord<String, MovieDetails>> {
  @Override
  public void onMessage(ObjectRecord<String, MovieDetails> record) {
    ...
  }
}
opsForZSet metodu
Şöyle yaparız
this.redisTemplate
  .opsForZSet()
  .incrementScore("MyMovie", "Likes", 1)
  .subscribe();

Hiç yorum yok:

Yorum Gönder