草庐IT

java - 尝试在我的 Play2 应用程序中利用 Akka future 和发挥 promise

coder 2024-03-14 原文

在阅读 play2 文档时,我发现了这一点:

Because of the way Play 2.0 works, action code must be as fast as possible (i.e. non blocking). So what should we return as result if we are not yet able to compute it? The response should be a promise of a result!

哇!这当然让我对playakka产生了兴趣。和 akka . 我目前正在构建一个与 elasticsearch 集成的自动完成应用程序, 所以这将是一个完美的选择!

Controller :

public class AutoComplete extends Controller {

    @BodyParser.Of(value = BodyParser.Json.class)
    public static Result complete(final String term) {

        F.Promise<List<String>> list = Akka.future(new Callable<List<String>>() {
            public List<String> call() throws Exception {
                List<String> list = IndexService.find(term);
                return list;
            }
        });    

        return async(list.map(new F.Function<List<String>, Result>() {
            @Override
            public Result apply(List<String> list) throws Throwable {
                return ok(Json.toJson(list));
            }
        }));
}

服务:

public static List<String> find(final String term) {

        IndexQuery < SearchWord > query = SearchWord.find.query();
        query.setQuery("{\n" +
                "    \"bool\": {\n" +
                "        \"should\": [\n" +
                "            {\n" +
                "                \"text\": {\n" +
                "                    \"search_word.ngrams\": {\n" +
                "                        \"operator\": \"and\",\n" +
                "                        \"query\": \""+term+"\"\n" +
                "                    }\n" +
                "                }\n" +
                "            },\n" +
                "            {\n" +
                "                \"text\": {\n" +
                "                    \"search_word.full\": {\n" +
                "                        \"boost\": 1,\n" +
                "                        \"query\": \""+term+"\"\n" +
                "                    }\n" +
                "                }\n" +
                "            }\n" +
                "        ]\n" +
                "    }\n" +
                "}");
        IndexResults<SearchWord> indexResults = SearchWord.find.search(query);

        List<String> list = new ArrayList<String>();
        for(SearchWord word : indexResults.getResults()){
            list.add(word.getWord());
        }

        return list;
    }
}

搜索词:

@IndexType(name = "search_word")
public class SearchWord extends Index {

    // Find method static for request
    public static Index.Finder<SearchWord> find = new Index.Finder<SearchWord>(SearchWord.class);

    public enum WordType {
        NAME,
        STRONG_SEARCH_WORD,
        WEAK_SEARCH_WORD,
        BANNED
    }

    private String word;
    private WordType wordType;

    public SearchWord() {
    }

    public SearchWord(IndexWord indexWord) {
        super.id = ""+indexWord.getId();
        this.word = StringUtils.lowerCase(indexWord.getWord());
        this.wordType = WordType.valueOf(indexWord.getType());
    }

    public String getId() {
        return super.id;
    }

    public void setId(String id) {
        super.id = id;
    }

    public String getWord() {
        return word;
    }

    public void setWord(String word) {
        this.word = word;
    }

    public WordType getWordType() {
        return wordType;
    }

    public void setWordType(WordType wordType) {
        this.wordType = wordType;
    }

    @Override
    public Map toIndex() {
        HashMap map = new HashMap();
        map.put("id", super.id);
        map.put("word", word);
        map.put("word_type", wordType.toString());
        return map;
    }

    @Override
    public Indexable fromIndex(Map map) {
        if (map == null) {
            return this;
        }
        this.word = (String) map.get("word");
        this.wordType = WordType.valueOf((String)map.get("word_type"));
        return this;
    }


}

代码工作得很好,但我必须说我不确定我是否正确地实现了它。我真的很难理解文档。 所以我的问题基本上是:

  1. 我是否正确实现了 Future 和 Promise?
  2. 创建一个自定义 actor 并在该 actor 中执行索引会更好吗 搜索,如文档中的示例:

=====

 return async(
        Akka.asPromise(ask(myActor,"hello", 1000)).map(
          new Function<Object,Result>() {
            public Result apply(Object response) {
              return ok(response.toString());
            }
          }
        )
      );
  1. 也许你有一些我还没有找到的很好的例子?

最佳答案

据我所知,您的代码完全没问题。

我可能错了,但我认为第二个选项严格等同于第一个选项,因为 Akka.future() 方法是 Akka.promise( ) 方法。

来自Akka class source code of Play 2.0.4 :

/**
 * Executes a block of code asynchronously in the application Akka Actor system.
 */
public static <T> Promise<T> future(java.util.concurrent.Callable<T> callable) {
    return asPromise(akka.dispatch.Futures.future(callable, system().dispatcher()));
}

关于java - 尝试在我的 Play2 应用程序中利用 Akka future 和发挥 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14136594/

有关java - 尝试在我的 Play2 应用程序中利用 Akka future 和发挥 promise的更多相关文章

  1. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  2. ruby-on-rails - Rails 应用程序之间的通信 - 2

    我构建了两个需要相互通信和发送文件的Rails应用程序。例如,一个Rails应用程序会发送请求以查看其他应用程序数据库中的表。然后另一个应用程序将呈现该表的json并将其发回。我还希望一个应用程序将存储在其公共(public)目录中的文本文件发送到另一个应用程序的公共(public)目录。我从来没有做过这样的事情,所以我什至不知道从哪里开始。任何帮助,将不胜感激。谢谢! 最佳答案 无论Rails是什么,几乎所有Web应用程序都有您的要求,大多数现代Web应用程序都需要相互通信。但是有一个小小的理解需要你坚持下去,网站不应直接访问彼此

  3. ruby - 无法运行 Rails 2.x 应用程序 - 2

    我尝试运行2.x应用程序。我使用rvm并为此应用程序设置其他版本的ruby​​:$rvmuseree-1.8.7-head我尝试运行服务器,然后出现很多错误:$script/serverNOTE:Gem.source_indexisdeprecated,useSpecification.Itwillberemovedonorafter2011-11-01.Gem.source_indexcalledfrom/Users/serg/rails_projects_terminal/work_proj/spohelp/config/../vendor/rails/railties/lib/r

  4. ruby-on-rails - Rails 应用程序中的 Rails : How are you using application_controller. rb 是新手吗? - 2

    刚入门rails,开始慢慢理解。有人可以解释或给我一些关于在application_controller中编码的好处或时间和原因的想法吗?有哪些用例。您如何为Rails应用程序使用应用程序Controller?我不想在那里放太多代码,因为据我了解,每个请求都会调用此Controller。这是真的? 最佳答案 ApplicationController实际上是您应用程序中的每个其他Controller都将从中继承的类(尽管这不是强制性的)。我同意不要用太多代码弄乱它并保持干净整洁的态度,尽管在某些情况下ApplicationContr

  5. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  6. ruby-on-rails - 如何在我的 Rails 应用程序 View 中打印 ruby​​ 变量的内容? - 2

    我是一个Rails初学者,但我想从我的RailsView(html.haml文件)中查看Ruby变量的内容。我试图在ruby​​中打印出变量(认为它会在终端中出现),但没有得到任何结果。有什么建议吗?我知道Rails调试器,但更喜欢使用inspect来打印我的变量。 最佳答案 您可以在View中使用puts方法将信息输出到服务器控制台。您应该能够在View中的任何位置使用Haml执行以下操作:-puts@my_variable.inspect 关于ruby-on-rails-如何在我的R

  7. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

  10. ruby-on-rails - 如何在 Gem 中获取 Rails 应用程序的根目录 - 2

    是否可以在应用程序中包含的gem代码中知道应用程序的Rails文件系统根目录?这是gem来源的示例:moduleMyGemdefself.included(base)putsRails.root#returnnilendendActionController::Base.send:include,MyGem谢谢,抱歉我的英语不好 最佳答案 我发现解决类似问题的解决方案是使用railtie初始化程序包含我的模块。所以,在你的/lib/mygem/railtie.rbmoduleMyGemclassRailtie使用此代码,您的模块将在

随机推荐