什么是单例类?它可以帮助我为两个相关服务运行一个类的单个实例吗?
这可能听起来很复杂,但我无论如何都会问:
我正在运行一个使用类 X 的服务 A。我想启动另一个服务 B,除了新类之外,它还使用类 A 。
服务A已在运行。我对服务B进行了热部署。
这是真正的问题 - 服务B将使用类X的相同实例还是单独的实例。单例类在这里如何帮助我?
This might sound complex but i will ask anyway:
I am running a service A which uses class X. I want to start another service B which uses classes A besides new classes.
Service A is already running. I do a hot deployment of Service B.
Here is the real question - Will Service B use the same instance of class X or a separate instance. How can singleton class help me here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
每个服务都将在其自己的操作系统(OS)进程空间中运行,并且每个进程空间都有其自己的类实例。 “单例”类通常使用类中的静态字段进行编码,这些静态字段对于代码运行所在的进程空间来说是本地的,所以不,它们不会共享单例。每个都会得到它自己的实例。
但是,您可以使用一些外部共享同步过程来完成您想要做的事情(例如,通过任何 java 等效项将单例暴露给 .Net Remoting(或 WCF) - 一个网络公开端点,编码为使用单例,并且让您的服务“连接到”并使用该远程可访问的单例)
Each Service will run in it's own operating System (OS) Process space, and each process space has it's own class instances. A "singleton" class is normally coded using static fields in a class, which would be local to the process space the code was running in, so no, they will not share singletons. Each will get it's own instance.
You can do what you are trying to do, however, using some external shared synchronization process, (for example, exposing a singleton over whatever the java equivilent is to .Net Remoting (or WCF) - a network exposed endpoint which is coded to use a Singleton, and have both your services "connect to" and use that remotely accessible Singleton)
我不熟悉 Java Web 服务如何运行的细节,但如果它们都在同一个虚拟机中运行,那么我认为这些类将在虚拟机中的所有应用程序之间共享,因此静态字段将被共享。由于单例模式通常是通过将单个实例附加到静态成员来完成的,因此单例将是共享的。
这基于:廉洁代码讲座 - “全局状态和单例”
您应该能够通过编写两个简单的 Web 服务来测试它。一个对单例执行某些操作,例如设置一个标志,另一个检查它。
I'm not familiar with the details of how Java Web services are run, but if they are both running in the same VM then I think the classes would be shared across all applications in the VM and static fields would therefore be shared. Since the Singleton pattern is usually accomplished by attaching a single instance to a static member, the Singleton would be shared.
This based on: The Clean Code Talks - "Global State and Singletons"
You should be able to test it out by writing two simple Web services. One that does something to the singleton, such as set a flag, and another that checks for it.