0

我需要创建一个在 Controller 和 Model 类之间共享的缓冲区(LinkedList)。我在模型类中创建了这个缓冲区

public class ServerController {

    private LinkedList<JsonNode> data; /* buffer */
    private static ServerController controller;

    public static ServerController getServerController(){
        return controller;
    }

    private ServerController() {
    }

我使用另一个模型类中的方法写入此缓冲区,并尝试从为 GET 请求提供服务的控制器方法中读取值,以便将数据返回给请求它的客户端。

    @BodyParser.Of(Json.class)
    public static Result getData() {
        ObjectNode result = play.libs.Json.newObject();
        LinkedList<JsonNode> data = ServerController.getController().getData();
        result.put("value", data.toString());
        return ok(result);
    }

问题是正在写入的缓冲区不是控制器正在读取的缓冲区。似乎 Play 正在实例化该类的另一个实例ServletController(即使我已将其设为单例)。如何使两个进程之间共享缓冲区?

在这种情况下,类加载器是否加载了 2 个不同的实例?

4

1 回答 1

3

The play framework is a stateless framework, you should not have a memory between requests in the controller layer.

But a common approach is to use the cache API:

http://www.playframework.org/documentation/2.0.4/JavaCache

Using this simple API you can store data in the cache:

Cache.set("item.key", frontPageNews);
You can retrieve the data later:

News news = Cache.get("item.key");
于 2012-11-19T06:03:44.527 回答