【问题标题】:How to get DB Response如何获得数据库响应
【发布时间】:2022-01-11 15:33:59
【问题描述】:
package com.example.demo.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener; 
import org.springframework.stereotype.Service;

import com.example.demo.User;
import com.example.demo.UserRepository;

@Service 
public class MessageConsumer {
  
    @Autowired
    UserRepository userrepo;
    @Autowired
    EmailSenderService senderservice;

    @KafkaListener(topics="k2-topic",groupId="mygroup2")

    public void consumeFromTopic(String message) {
        System.out.println("consumed message "+message);
        String msg = message;
        String vin = msg.substring(0, 17);
        String verified = msg.substring(17, 18);
        int sp = Integer.parseInt(msg.substring(18,21));
        String alert = msg.substring(21,22);
        char ch = alert.charAt(0);
        String timeStamp = msg.substring(22);
        String bd = "Hai There !\n Your CAR VIN NO IS : "+vin+"\nYou're crossing your SPEED 
        LIMIT : "+sp+"\nPlease Drive slowly\nSafe driving saves life.";

        if(ch=='y')  senderservice.sendEmail(bd);

        User obj = new User(vin,verified,sp,alert,timeStamp);
        userrepo.save(obj);
    } 
}

在这段代码中,我收到了来自 kafka 的消息。基于该消息,我在将消息存储到数据库之前发送邮件。但我想在存储数据后发送邮件。如果 db 的响应正常,那么我将发送邮件,否则不会。那么如何获得数据库响应以及如何知道消息是否存储在数据库中。我正在使用 cassandra DB。请帮忙。

【问题讨论】:

标签: java spring spring-boot cassandra


【解决方案1】:

如果数据库插入不成功,那么你会得到一个异常。
如果您没有在您的服务或存储库中捕获此异常,则此异常将被 Spring Web 捕获。

因此,您可以在运行save 方法后发送电子邮件。

package com.example.demo.consumer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener; 
import org.springframework.stereotype.Service;

import com.example.demo.User;
import com.example.demo.UserRepository;

@Service 
public class MessageConsumer {
  
    @Autowired
    UserRepository userrepo;
    @Autowired
    EmailSenderService senderservice;

    @KafkaListener(topics="k2-topic",groupId="mygroup2")

    public void consumeFromTopic(String message) {
        System.out.println("consumed message "+message);
        String msg = message;
        String vin = msg.substring(0, 17);
        String verified = msg.substring(17, 18);
        int sp = Integer.parseInt(msg.substring(18,21));
        String alert = msg.substring(21,22);
        char ch = alert.charAt(0);
        String timeStamp = msg.substring(22);
        String bd = "Hai There !\n Your CAR VIN NO IS : "+vin+"\nYou're crossing your SPEED 
        LIMIT : "+sp+"\nPlease Drive slowly\nSafe driving saves life.";

        User obj = new User(vin,verified,sp,alert,timeStamp);
        userrepo.save(obj);

        if(ch=='y')  senderservice.sendEmail(bd);
    } 
}
  • 如果插入不成功,则不会发送电子邮件,因为服务器会抛出异常。
  • 如果插入成功,则发送电子邮件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-12-08
    • 2017-08-16
    • 2011-03-03
    相关资源
    最近更新 更多