如何保持App Engine Servlet监听Firebase

Sau*_*ron 5 google-app-engine android servlets firebase

我正在以下位置关注该教程:https : //cloud.google.com/solutions/mobile/firebase-app-engine-android-studio

我一切正常,电子邮件每隔2分钟发送一次。但是,我现在希望将其扩展为仅在Firebase节点上的数据更改后才触发发送电子邮件,而不是每2分钟发送一次消息。

为了测试,我cron.xml从以下位置替换了文件:

<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
   <cron>
       <url>/hello</url>
       <description>Send me an email of outstanding items in the morning</description>
       <schedule>every 2 minutes</schedule>
   </cron>
</cronentries>
Run Code Online (Sandbox Code Playgroud)

至:

<?xml version="1.0" encoding="UTF-8"?>
<cronentries/>
Run Code Online (Sandbox Code Playgroud)

清除计划任务。

但是,现在在Firebase数据库中进行更改后,就再也不会发送电子邮件了。

如何让我的App Engine服务器“侦听” firebase节点,并随后onDataChanged进行实时给出的操作?

MyServlet类:

public class MyServlet extends HttpServlet {
    static Logger Log = Logger.getLogger("com.example.username.myapplication.backend.MyServlet");

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
        Log.info("Got cron message, constructing email.");

        //Create a new Firebase instance and subscribe on child events.
        Firebase firebase = new Firebase("[firebase ref]");
        firebase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                // Build the email message contents using every field from Firebase.
                final StringBuilder newItemMessage = new StringBuilder();
                newItemMessage.append("This should arrive very closely after changing the data");


                //Now Send the email
                Properties props = new Properties();
                Session session = Session.getDefaultInstance(props, null);
                try {
                    Message msg = new MimeMessage(session);
                    //Make sure you substitute your project-id in the email From field
                    msg.setFrom(new InternetAddress("anything@[app-engine].appspotmail.com",
                            "Todo Nagger"));
                    msg.addRecipient(Message.RecipientType.TO,
                            new InternetAddress("myEmail@gmail.com", "Recipient"));
                    msg.setSubject("Feast Email Test");
                    msg.setText(newItemMessage.toString());
                    Transport.send(msg);
                } catch (MessagingException | UnsupportedEncodingException e) {
                    Log.warning(e.getMessage());
                }
            }

            public void onCancelled(FirebaseError firebaseError) {
            }
        });
    }

}
Run Code Online (Sandbox Code Playgroud)

Ben*_*lfe 3

你的问题实际上是一个关于AppEngine以及如何创建一个自动启动并自动执行一些初始化的Servlet的问题。

您需要保持手动缩放,但请按照此处的步骤操作: https: //cloud.google.com/appengine/docs/java/config/appconfig#using_a_load-on-startup_servlet

用于在 init() 而不是 http 请求上设置侦听器。您所尝试的绝对是可能的,并且已经在其他地方看到过它的运行。