I have a method which opens a web service session. The method structure looks something like this:
public Soap getServicePort()
{
//TODO: Open a connect and return the SOAP object
return soap;
}
I have a requirement to add a monitor straight after the return. The monitor's job is to wait for 2hrs and in-activate the session and rebuild a new one - well reason been the current session will be invalid at that time and therefore we need to rebuild and re开发者_如何学编程turn a new session.
Can anyone suggest a reasonable way of doing this?
Thanks.
public Soap getServicePort()
{
try {
return soap;
} finally {
// add monitor here.
}
}
But be careful: monitor should not throw exceptions. Put its initiation ito try/catch.
Probably better solution is wraper pattern. For example you can define interface with method getServicePort() and 2 implementations: one your real implementation and other that wraps real and adds monitor. This solution is more flexible. For example probably you will have to create your monitor afeter other methods and even after other methods implemented in other classes.
In this case you can use AOP. There are several ways to use it. One is using Dynamic Proxy of java. Other is using special tools like AspectJ.
So, choose your solution. Your choice should depend on the complexity of your task and number of methods/classes that required to implement this functionality. If it is only one method use try/finally, if it is several methods in the same class, use wrapper pattern. If it is required for several methods in several classes use Proxy or AspectJ.
You can try logic
like this.. no need to have monitor on this
private Soap soap = null;
public Soap getServicePort()
{
try {
if(soap!=null && soap.isValide()){
// not sure about the method isValide(), some condition to check session
return soap;
}else{
// create new soap & return
return soap;
}
} catch(Exception e){
}// END Catch
}// END MEthod
Call the method as many times as you want...
精彩评论