Closed PhilAndrew closed 10 years ago
If you use the factories (object apply methods), it will be up to you to close the resource using close method, like that:
val ssh= SSH(host="localhost", username="test")
try {
ssh.execute("ls")
} finally {ssh.close()}
But SSH object brings helper methods that auto-close resource for you :
val result = SSH.once(host="localhost", username="test") { ssh =>
ssh.execute("ls")
}
Another one, with a persited shell session
val result = SSH.shell(host="localhost", username="test") {sh =>
s"""My name is ${sh.execute("hostname")} and my uptime is ${sh.execute("uptime")}"""
}
In that last case, both commands hostname and uptime are executed within the same shell, the proof :
val result = SSH.shell(host="localhost", username="test") {sh =>
sh.execute("HELLO=`hostname`")
sh.execute("echo hello $HELLO")
}
You can also define such function in order to use your own safe autoclose mechanism :
def using[R, T<%{def close()}](getres: =>T)(proc : T => R):R = {
val res=getres
try {proc(res)} finally {res.close}
}
val result = using(SSH(host="localhost", username="test")) { ssh =>
ssh.execute("ls")
}
Can you explain how the resource of the connection is managed?
Lets say I have a class with a method doWork and this method does SSH commands frequently and gets called frequently, I think I should make a member of this class as a lazy val as:
lazy val ssh = SSH(?, ?, ?)
I am expecting that when I go to use ssh the first time, it will open the connection, then since the object is around as a member of this class, it will keep using the same connection.
Is this how it works?
What if I kept re-creating the SSH(...), would it cache the connection?