我一直听说Global对象将被弃用,将一些代码放在Global类的.onStart()中并不是一个好习惯。如果是这样,有什么替代方案?
一群人here说要使用Global对象,但这也是4年前。
我目前有以下需求。我在游戏中编写了一个消费来自消息队列的消息(在我的情况下,即NSQ(目前没有Camel绑定到它))并将这些消息发送给正在监听它的Web Socket客户端组。所以我希望消费者为每个主题初始化一次,并开始永远运行,直到应用程序本身终止。发生的事情是,当我向一个主题发送10条消息时,我只能看到5条消息通过,但是当我运行相同的确切方法时,#34; startNSQConsumer()"从下面的代码中单独的普通旧Java应用程序本身我可以看到所有10条消息。很明显,这与游戏有关,我不确定发生了什么。任何想法?
public class Global extends GlobalSettings {
private static final ExecutorService EXECUTOR_SERVICE = Executors.newSingleThreadScheduledExecutor();
@Override
public void onStart(Application application) {
EXECUTOR_SERVICE.submit(() -> {
startNSQConsumer();
});
super.onStart(application);
}
@Override
public void onStop(Application application) {
EXECUTOR_SERVICE.shutdown();
super.onStop(application);
}
private void startNSQConsumer() {
NSQLookup lookup = new DefaultNSQLookup();
Configuration config = Play.application().configuration();
List<String> topics = config.getStringList("TOPICS");
String nsqlookupdIP = config.getString("NSQLOOKUPD_IP");
int nsqlookupdPort = Integer.parseInt(config.getString("NSQLOOKUPD_PORT"));
lookup.addLookupAddress(nsqlookupdIP, nsqlookupdPort);
Logger.info("Using nsqlookup at " + nsqlookupdIP + ":" + nsqlookupdPort);
topics.forEach((topic) -> {
NSQConsumer consumer = new NSQConsumer(lookup, topic, topic + "_channel", (message) -> { // messages here will come from external system running on some other node
String receivedMessage = new String(message.getMessage());
//Logger.info(receivedMessage); // When I enable or disable this I only see 50% of the messages.
EventBusManager.getEventBus().publish(new MsgEnvelope(topic, receivedMessage)); // broadcast message to all Actors listening on a particular topic
message.finished();
}, new NSQConfig(), new NSQErrorCallback() {
@Override
public void error(NSQException x) {
Logger.error("Cause: " + x.getCause() + ", Message: " + x.getMessage());
}
});
consumer.start();
});
}
}
答案 0 :(得分:2)
您有两个问题,我将首先回答,然后您可以重构您的代码,以便在没有Global
的情况下运行,并查看问题是否仍然存在。如果是,则创建另一个问题。
<强> SCHEDULE 强>
在Playframework中,使用计划任务的最佳方法是Akka actor和Akka scheduler:https://www.playframework.com/documentation/2.5.x/JavaAkka。
你需要在演员中放置你的代码(没有EXECUTOR_SERVICE
,只有那个有用的部分):
@Singleton
public class NSQRunner extends UntypedActor{
public static final String name = "NSQRunner";
...
@Override
public void onReceive(Object msg) throws Throwable {
if(msg instanceof NSQRunnerProtocol.StartConsumer){
startNSQConsumer();
} else {
unhandled(msg);
}
}
private void startNSQConsumer() {
...
}
}
您可以将此演员视为来自Executors.newSingleThreadScheduledExecutor()
的线索。它会在收到告诉他这样做的消息时完成工作 - NSQRunnerProtocol.StartConsumer
。这是协议类:
public class NSQRunnerProtocol {
/**
* Start the NSQ consumer.
*
*/
public static class StartConsumer{}
}
现在您需要在应用程序启动时运行它。
这里是调度程序任务,它将在启动后1秒后运行你的actor:
@Singleton
public class Scheduler {
@Inject
public Scheduler(
final ActorSystem system,
final Configuration configuration,
@Named(NSQRunner.name) ActorRef nsqRunner) {
system.scheduler().scheduleOnce(
Duration.create(1, TimeUnit.SECONDS),
nsqRunner,
new NSQRunnerProtocol.StartConsumer(),
system.dispatcher(),
null);
}
}
现在您需要在应用程序中注册actor和scheduler。 Play框架有这个模块系统,所以你需要创建一个模块类:
package my.nsq
...
public class Module extends AbstractModule implements AkkaGuiceSupport {
@Override
protected void configure() {
// Bind actors.
bindActor(NSQRunner.class, NSQRunner.name);
// Bind scheduler, it will run on the start of application.
bind(Scheduler.class).asEagerSingleton();
}
}
并在conf/application.conf
注册:
play.modules {
...
enabled += my.nsq.Module
}
暂停
在这种情况下,如果您需要某些工作onStop
应用程序,那么您需要通过ApplicationLifecycle
方法注入addStopHook
和一个停止挂钩:https://www.playframework.com/documentation/2.5.x/PluginsToModules#Create-a-Module-class。< / p>
以下是数据库访问单例的一个示例:
@Singleton
public class Couchbase {
private static ALogger logger = Logger.of(Couchbase.class);
private final Cluster cluster;
private final Bucket bucket;
@Inject
public Couchbase(ApplicationLifecycle lifecycle, Configuration configuration) {
// Read the database configuration from the setting.
final String clusterName = configuration.getString("couchbase.cluster");
final String bucketName = configuration.getString("couchbase.bucket.name");
final String bucketPassword = configuration.getString("couchbase.bucket.password");
final CouchbaseEnvironment env = DefaultCouchbaseEnvironment
.builder()
.queryEndpoints(1)
.autoreleaseAfter(50000)
.queryTimeout(20000)
.retryStrategy(FailFastRetryStrategy.INSTANCE)
.reconnectDelay(Delay.fixed(5, TimeUnit.SECONDS))
.build();
logger.debug(
"Connect to the couche: cluster \"{}\", bucket: \"{}\"",
clusterName,
bucketName);
// Connect.
cluster = CouchbaseCluster.create(env, clusterName);
bucket = cluster.openBucket(bucketName, bucketPassword);
// Create a default index.
bucket.bucketManager().createN1qlPrimaryIndex(true, false);
// Special operations on the application shutdown.
lifecycle.addStopHook(() -> {
// Close the connection on application shutdown.
env.shutdown();
cluster.disconnect();
// Couchbase close the connection synchronously
// so we need just return an empty CompletableFuture.
return CompletableFuture.completedFuture(null);
});
}
/**
* @return the application bucket
*/
public Bucket getBucket() {
return bucket;
}
}
您可以在Module
中绑定此对象:
bind(Couchbase.class).asEagerSingleton();
然后你可以注射它,即使是你的演员:
public class NSQRunner ...
@Inject
public NSQRunner(Couchbase couchbase){
...
}
}
你可以像s Couchbase
那样在singelton中尽你所能,但我的观点是演员要好得多。