我有一个访问数据库的 Jersey 资源。基本上它在资源的初始化中打开一个数据库连接。对资源的方法执行查询。
我观察到,当我不使用@Singleton 时,每次请求都会打开数据库。而且我们知道打开连接真的很昂贵,对吧?
所以我的问题是,我应该指定资源是单例的,还是根据请求保留它真的更好,尤其是在资源连接到数据库时?
我的资源代码如下所示:
//Use @Singleton here or not?
@Path(/myservice/)
public class MyResource {
private ResponseGenerator responser;
private Log logger = LogFactory.getLog(MyResource.class);
public MyResource() {
responser = new ResponseGenerator();
}
@GET
@Path("/clients")
public String getClients() {
logger.info("GETTING LIST OF CLIENTS");
return responser.returnClients();
}
...
// some more methods
...
}
我使用类似于以下的代码连接到数据库:
public class ResponseGenerator {
private Connection conn;
private PreparedStatement prepStmt;
private ResultSet rs;
public ResponseGenerator(){
Class.forName("org.h2.Driver");
conn = DriverManager.getConnection("jdbc:h2:testdb");
}
public String returnClients(){
String result;
try{
prepStmt = conn.prepareStatement("SELECT * FROM hosts");
rs = prepStmt.executeQuery();
...
//do some processing here
...
} catch (SQLException se){
logger.warn("Some message");
} finally {
rs.close();
prepStmt.close();
// should I also close the connection here (in every method) if I stick to per request
// and add getting of connection at the start of every method
// conn.close();
}
return result
}
...
// some more methods
...
}
对代码最佳实践的一些评论也会有所帮助。