2 Kasım 2023 Perşembe

Neural Autonomic Transport System (NATS) Kullanımı

Giriş
Açıklaması şöyle
History and Evolution
NATS was originally created by Derek Collison, who, inspired by his experiences with building messaging systems, aimed to craft a messaging solution that embodies simplicity and performance. Over time, as cloud architectures grew in popularity, NATS emerged as a popular choice, primarily because of its inherent characteristics that matched the requirements of cloud-native systems.

Maven
Şu satırı dahil ederiz
<dependency>
    <groupId>io.nats</groupId>
    <artifactId>java-nats</artifactId>
    <version>latest_version</version>
</dependency>
Docker
Şöyle yaparız
docker run -d -p 4222:4222 -p 8222:8222 --name nats-main nats:latest

Go to http://localhost:8222
Connection Sınıfı
constructor
application.properties şöyle olsun
nats.url=nats://localhost:4222
Şöyle yaparız
@Configuration
public class NatsConfig {
    
  @Value("${nats.url}")
  private String natsUrl;

  @Bean
  public Connection natsConnection() throws IOException, InterruptedException {
    Options options = new Options.Builder().server(natsUrl).build();
    return Nats.connect(options);
  }
}
publish metodu
Şöyle yaparız
@Autowired
private Connection natsConnection;

public void sendMessage(String subject, String message) {
  natsConnection.publish(subject, message.getBytes(StandardCharsets.UTF_8));
}
subscribe metodu
Şöyle yaparız
@Autowired
private Connection natsConnection;

public void subscribeToSubject(String subject) {
  natsConnection.subscribe(subject, msg -> {
    String receivedMessage = new String(msg.getData(), StandardCharsets.UTF_8);
    // Handle and process the received message
  });
}


Hiç yorum yok:

Yorum Gönder