identify whether is code running on app engine run

2019-04-07 09:11发布

How can one identify whether some code (a serv-let or a simple class) is running on Google App Engine run-time (Java) so that one can decide whether to utilize app engine's specific libraries or not? Is there some reliable runtime enviroment ID for that?

6条回答
【Aperson】
2楼-- · 2019-04-07 09:49

You can check the com.google.appengine.runtime.version property:

String appEngineVersion = System.getProperty("com.google.appengine.runtime.version");

If it's set, it's App Engine.

But I would consider using separate build targets instead, to avoid the runtime overhead.

查看更多
何必那么认真
3楼-- · 2019-04-07 09:52

I saw no type-safe solution here so here it is:

if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) {
    // The app is running on App Engine...
}
查看更多
Animai°情兽
4楼-- · 2019-04-07 09:53

As explained here you can check the following property:

String environment = System.getProperty(
    "com.google.appengine.runtime.environment")

environment is "Production" when running on App Engine, and "Development" when running in the development server.

查看更多
Rolldiameter
5楼-- · 2019-04-07 09:57

There is another way to do this as well. This is explained well in gaevfs's documentation on how to write Portable Code: http://code.google.com/p/gaevfs/wiki/ApplicationPortability

Of interest to you is the following line:

boolean isGoogleAppEngine = getServletContext().getServerInfo().contains( "Google" );
查看更多
倾城 Initia
6楼-- · 2019-04-07 10:05

similar to what @Reza wrote, but a bit cleaner:

use SystemProperty.environment.value() to get "Production" when running on App Engine, and "Development" when running in the development server.

查看更多
在下西门庆
7楼-- · 2019-04-07 10:15

As @Matthew Flaschen said, there are system properties that you can check to determine if GAE is present or not. This link gives the details.

If you go down this route, your application needs to be built so that the main code has no static dependencies on the GAE classes; i.e. no imports or other references to GAE packages and classes in the code (apart GAE class names, etc in String literals). All dependencies have to be isolated to code that gets loaded using Class.forName(String) AFTER you've determined whether or not GAE is present.

This represents a non-trivial overhead:

  • You'll probably end up with an extra Adapter interface and (at least) two implementations for the GAE and non-GAE cases.
  • You've got the (minor) runtime overheads of dynamically loading the relevant class at startup, and calling through the Adapter interface.
  • Your JAR file is that much bigger as a result.
  • You now have to test on two platforms.

On the other hand, you do have the potential advantage of having one JAR that works in both GAE and non-GAE contexts.

查看更多
登录 后发表回答