在应用程序范围中存储变量 java glassfish
我试图在 glassfish Web 服务的应用程序范围中存储一个数字
Web 服务:
@WebService()
public class datacheck {
//TODO 080 disable sql_log in the settings of hibernate
//TODO 090 check todo's from webservice_1
private int counter = 5;
当我请求计数器变量时,我得到 5 并
@WebMethod(operationName = "increaseCounter")
public Integer increaseCounter() {
counter++;
return counter;
}
返回 6 但是 当我之后尝试执行此操作时,我再次得到 5:
@WebMethod(operationName = "getCounter")
public Integer getCounter() {
return counter;
}
如何存储可用于 Web 服务中所有方法的变量?
i'm trying to store a number in the applicationscope of a glassfish webservice
the webservice:
@WebService()
public class datacheck {
//TODO 080 disable sql_log in the settings of hibernate
//TODO 090 check todo's from webservice_1
private int counter = 5;
when i request the counter variable i get 5
and
@WebMethod(operationName = "increaseCounter")
public Integer increaseCounter() {
counter++;
return counter;
}
returns 6 but
when i try to do this afterwards i get 5 again:
@WebMethod(operationName = "getCounter")
public Integer getCounter() {
return counter;
}
how do i store a variable that is available for all methods in the webservice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这在一定程度上取决于您的用例和架构。如果每个用户都应该看到增量计数器的结果,那么您可以在代码中静态声明它。
不过,只有当您的应用程序中只有一个 JVM 并且需要仔细考虑同步时,这才有效。
或者,您可以将其保留在外部(例如数据库或文件)
This depends on your use case and architecture to an extent. If every user should see the result of increment counter then yo could declare it statically in your code.
This will only work if you have only one JVM in your application though and would require careful thought about synchronization.
Alternatively you could persist it externally ( to a database or file for example )
实现 Singleton 模式应该可行。您最终将在整个 JVM 中得到相同的实例。但要注意:从不同线程写入单例可能是满足锁,这样就可能是龙!
如果您想限制反对一个线程(我认为 glassfish 是每个请求一个线程,但不要引用我:)
Implementing the Singleton pattern should work. you will end up with the same instance in the whole JVM. Beware though: writing to a singleton from different threads might be a contented lock, and that way be dragons!
There's also ThreadLocal if you want to constraint an object to one thread (i think glassfish is one thread per request but dont cite me :)