【问题标题】:how to call a resource url running on the same AppEngine instance from a servlet如何从 servlet 调用在同一 AppEngine 实例上运行的资源 url
【发布时间】:2012-06-04 07:35:12
【问题描述】:

我已经使用 Jersey 实现了一些 RESTful 资源 url,例如 http://myapp.appspot.com/temperature/get。我还有一个 servlet 在我想调用资源 url 的同一个 AppEngine 实例上运行。我的问题是我不知道如何引用 servlet 所在的正在运行的 Appengine 实例。换句话说,我想使用相当于 127.0.0.1 或 $SERVER_HOME 的 AppEngine。

我最初的方法是在 servlet 中做这样的事情:

URL url = new URL(getServletContext().getContextPath());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

,但 getContextPath() 返回一个空字符串(应该如此,因为我没有将应用程序名称放在 url 中。

如何获取对应用程序基本位置的引用,以便引用其中运行的 url 资源?提前致谢!

【问题讨论】:

  • 为什么不简单地让restful接口和其余代码调用相同的服务代码呢?没有理由为自己制作 URLFetches。

标签: java google-app-engine servlets


【解决方案1】:

要检查 URL 是否存在于同一台服务器计算机中,请执行以下操作:

String host = remoteHost;
int port = remotePort;
String remoteContext = //the application root you want to access;
String remtoePath =  // the servlet or path you want to access;
if((host.equals(request.getServerName()) || host.equals("localhost")) 
      && port == request.getServerPort(){
   ....
  ServletContext context = servletContext.get(remoteContext);
  RequestDispatcher dispatcher = context.getRequestDispatcher(remotePath);
     //if you want to forward
  //dispatcher.forward(request, response);
     //if you want to include
  //dispatcher.include(request, response);

}

【讨论】:

  • Ramesh: request.getServerName() 是我要找的。现在它起作用了。谢谢!
【解决方案2】:

相同的实例或相同版本的代码?您不能针对同一实例。没有办法做到这一点。您可以定位相同的版本(yourdomain.appspot.com 或 latest.yourdomain.appspot.com)。如果您想知道您的应用程序是否在开发服务器中运行,您可以使用 SystemProperty 类

https://developers.google.com/appengine/docs/java/javadoc/com/google/appengine/api/utils/SystemProperty

如果你想定位一个版本,你应该知道 url...如果不是,请使用 Ramesh 的建议。通常,我们在 servlet 中设置一个静态属性类,用于保存当前活动域的名称。或者只是使用 TaskQueues...它们非常适合此目的。

【讨论】:

  • 对不起,你是对的......我的意思是相同版本的代码,而不是实例。我仍然需要习惯 Google AppEngine 语义/思维模式,其中版本控制被滚动到服务器运行时环境中。
  • 那么您基本上有 3 个选择:1)ramesh 的建议,2)将应用程序/版本的位置存储在您的代码或加载到属性中的配置文件中,3)调用任务队列。如果此 servlet 不是用于用户交互,而是您需要运行的“服务”,那么任务队列非常棒。
猜你喜欢
  • 2011-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 1970-01-01
  • 2018-05-05
  • 2019-06-09
  • 1970-01-01
相关资源
最近更新 更多