【发布时间】:2018-08-24 06:30:10
【问题描述】:
架构:我有一个 Web 应用程序,我在其中与 Datastore 和一个客户端 (raspberry pi) 进行交互,该客户端使用 Google Cloud Endpoints 从 Web 应用程序调用方法。
我必须补充一点,我对 Web 应用程序不是很熟悉,我认为 setConsumed() 方法有问题,因为我可以在应用引擎仪表板中看到 /create 的调用,但 /setConsumed 没有条目.
我可以使用 objectify 将实体添加到数据存储区:
//client method
private static void sendSensorData(long index, String serialNumber) throws IOException {
SensorData data = new SensorData();
data.setId(index+1);
data.setSerialNumber(serialNumber);
sensor.create(data).execute();
}
//api method in the web application
@ApiMethod(name = "create", httpMethod = "post")
public SensorData create(SensorData data, User user) {
// check if user is authenticated and authorized
if (user == null) {
log.warning("User is not authenticated");
System.out.println("Trying to authenticate user...");
createUser(user);
// throw new RuntimeException("Authentication required!");
} else if (!Constants.EMAIL_ADDRESS.equals(user.getEmail())) {
log.warning("User is not authorised, email: " + user.getEmail());
throw new RuntimeException("Not authorised!");
}
data.save();
return data;
}
//method in entity class SensorData
public Key<SensorData> save() {
return ofy().save().entity(this).now();
}
但是,我无法使用以下代码从数据存储中删除实体。
编辑: Stackdriver Logging 中有很多关于 create-request 的日志,但没有setConsumed()。因此,尽管两种方法都在同一个类中,但似乎调用甚至都没有到达 API。
编辑 2:当我从 Powershell 调用该方法时,实体被删除,因此问题很可能出在客户端。
//client method
private static void removeSensorData(long index) throws IOException {
sensor.setConsumed(index+1);
}
//api method in the web application
@ApiMethod(name = "setConsumed", httpMethod = "put")
public void setConsumed(@Named("id") Long id, User user) {
// check if user is authenticated and authorized
if (user == null) {
log.warning("User is not authenticated");
System.out.println("Trying to authenticate user...");
createUser(user);
// throw new RuntimeException("Authentication required!");
} else if (!Constants.EMAIL_ADDRESS.equals(user.getEmail())) {
log.warning("User is not authorised, email: " + user.getEmail());
throw new RuntimeException("Not authorised!");
}
Key serialKey = KeyFactory.createKey("SensorData", id);
datastore.delete(serialKey);
}
【问题讨论】:
-
您能否详细说明“我无法从数据存储中删除实体”是什么意思?您是否遇到异常(如果是,您能否在问题中添加堆栈跟踪)?还是删除调用完成但实体并未实际删除的情况?
-
抱歉不准确。我没有任何例外。看起来调用正确完成,但数据存储中没有任何反应
-
这表明 Datastore 中没有此键的条目:
KeyFactory.createKey("SensorData", id)。您确定ofy().save().entity(this)创建的密钥与您在setConsumed()中创建的密钥匹配吗? -
我确定。我通过仪表板检查了数据存储,并且有一个具有以下键的实体:Key(SensorData, 1)。此外,
removeSensorData()仅在sendSensorData()之后被调用,我已经尝试使用(long) 1而不是index+1
标签: java google-cloud-platform google-cloud-datastore