內存資料庫jdbc
簡單來說就是用jdbc:h2:mem:h2db來建立內存模式,並建表,
然後jdbc:h2:tcp://192.168.20.141:8082/mem:h2db來訪問上面的內存資料庫
package test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.h2.tools.Server;
public class H2Demo {
private Server server;
private String port = "8082";
private static String sourceURL1 = "jdbc:h2:mem:h2db";
private static String sourceURL2 = "jdbc:h2:tcp://192.168.20.141:8082/mem:h2db";
private String user = "shorturl";
private String password = "123456";
public void startServer() {
try {
System.out.println("正在啟動h2...");
server = Server.createTcpServer(
new String[] { "-tcpPort", port }).start();
} catch (SQLException e) {
System.out.println("啟動h2出錯:" + e.toString());
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(e);
}
}
public void stopServer() {
if (server != null) {
System.out.println("正在關閉h2...");
server.stop();
System.out.println("關閉成功.");
}
}
public void useH2() {
try {
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection(sourceURL1,user, password);
Statement stat = conn.createStatement();
// insert data
stat.execute("CREATE MEMORY Table TEST(NAME VARCHAR)");
stat.execute("INSERT INTO TEST VALUES('Hello World')");
//stat.execute("delete mappedURL");
// use data
ResultSet result = stat.executeQuery("select name from test ");
int i = 1;
while (result.next()) {
System.out.println(i++ + ":" + result.getString("name"));
}
result.close();
stat.close();
conn.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void useH2i() {
try {
Class.forName("org.h2.Driver");
//Connection conn = DriverManager.getConnection("jdbc:h2:" + dbDir+";AUTO_SERVER=TRUE;MVCC=TRUE",user, password);
Connection conn = DriverManager.getConnection(sourceURL2,user, password);
Statement stat = conn.createStatement();
// use data
ResultSet result = stat.executeQuery("select name from test");
㈡ 內存資料庫主流的有哪些,並給出各自特點!
內存資料庫從范型上可以分為關系型內存資料庫和鍵值型內存資料庫。
在實際應用中內存資料庫主要是配合oracle或mysql等大型關系資料庫使用,關注性能。
作用類似於緩存,並不注重數據完整性和數據一致性。
基於鍵值型的內存資料庫比關系型更加易於使用,性能和可擴展性更好,因此在應用上比關系型的內存資料庫使用更多。
比較FastDB、Memcached和Redis主流內存資料庫的功能特性。
FastDB的特點包括如下方面:
1、FastDB不支持client-server架構因而所有使用FastDB的應用程序必須運行在同一主機上;
2、fastdb假定整個資料庫存在於RAM中,並且依據這個假定優化了查詢演算法和介面。
3、fastdb沒有資料庫緩沖管理開銷,不需要在資料庫文件和緩沖池之間傳輸數據。
4、整個fastdb的搜索演算法和結構是建立在假定所有的數據都存在於內存中的,因此數據換出的效率不會很高。
5、Fastdb支持事務、在線備份以及系統崩潰後的自動恢復。
6、fastdb是一個面向應用的資料庫,資料庫表通過應用程序的類信息來構造。
FastDB不能支持Java API介面,這使得在本應用下不適合使用FastDB。
Memcached
Memcached是一種基於Key-Value開源緩存伺服器系統,主要用做資料庫的數據高速緩沖,並不能完全稱為資料庫。
memcached的API使用三十二位元的循環冗餘校驗(CRC-32)計算鍵值後,將資料分散在不同的機器上。當表格滿了以後,接下來新增的資料會以LRU機制替換掉。由於 memcached通常只是當作緩存系統使用,所以使用memcached的應用程式在寫回較慢的系統時(像是後端的資料庫)需要額外的程序更新memcached內的資料。
memcached具有多種語言的客戶端開發包,包括:Perl、PHP、JAVA、C、Python、Ruby、C#。
Redis
Redis是一個高性能的key-value資料庫。redis的出現,很大程度補償了memcached這類keyvalue存儲的不足,在部分場合可以對關系資料庫起到很好的補充作用。它提供了C++、Java、Python,Ruby,Erlang,PHP客戶端。