Apache Ignite學習筆記:建立快取、儲存資料、讀取快取
使用Apache Ignite2.4 建立快取 、儲存資料、讀取快取
1 Ignite初始化
(1)初始化程式碼
//使用配置檔案 example-default.xml 初始化Ignite
Ignite ignite=Ignition.start("example-default.xml") ;
//或者不使用配置檔案
Ignite ignite=Ignition.start();
//是否設定為客戶端模式
Ignition.setClientMode(true);
初始化有兩種方式 1 使用配置檔案 2 不使用配置檔案如上
(2) Ignite Xml配置檔案
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd"> <bean id="ignite.cfg" class="org.apache.ignite.configuration.IgniteConfiguration"> <!-- Set to true to enable distributed class loading for examples, default is false. --> <property name="peerClassLoadingEnabled" value="true"/> <property name="cacheConfiguration"> <list> <!-- Partitioned cache example configuration (Atomic mode). --> <bean class="org.apache.ignite.configuration.CacheConfiguration"> <property name="name" value="xmlcache1"/> <property name="atomicityMode" value="ATOMIC"/> <property name="backups" value="1"/> </bean> </list> </property> <!-- Enable task execution events for examples. --> <property name="includeEventTypes"> <list> <!--Task execution events--> <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_STARTED"/> <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_FINISHED"/> <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_FAILED"/> <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_TIMEDOUT"/> <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_SESSION_ATTR_SET"/> <util:constant static-field="org.apache.ignite.events.EventType.EVT_TASK_REDUCED"/> <!--Cache events--> <util:constant static-field="org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_PUT"/> <util:constant static-field="org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_READ"/> <util:constant static-field="org.apache.ignite.events.EventType.EVT_CACHE_OBJECT_REMOVED"/> </list> </property> <!-- Explicitly configure TCP discovery SPI to provide list of initial nodes. --> <property name="discoverySpi"> <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi"> <property name="ipFinder"> <!-- Ignite provides several options for automatic discovery that can be used instead os static IP based discovery. For information on all options refer to our documentation: http://apacheignite.readme.io/docs/cluster-config --> <!-- Uncomment static IP finder to enable static-based discovery of initial nodes. --> <!--<bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">--> <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder"> <property name="addresses"> <list> <!-- In distributed environment, replace with actual host IP address. --> <value>127.0.0.1:47500..47509</value> </list> </property> </bean> </property> </bean> </property> </bean> </beans>
快取有三種方式 Local, Backup, partition
2 使用Apache Ignite建立快取Cache
(1) 建立快取程式碼
CacheConfiguration<Integer, Person > cfg = new CacheConfiguration<Integer,Person >(); //定義一個快取配置 cfg.setName("TestCache"); //必須設定名字 cfg.setCacheMode(CacheMode.PARTITIONED);//儲存方式 PARTITIONED適合分散式儲存 cfg.setIndexedTypes(Integer.class, TestClass.class); //必須設定索引類否則只能以key-value方式查詢 IgniteCache<Integer, Person > Cache = ignite.getOrCreateCache(cfg);//根據配置建立快取 //可以給快取的資料設定一個過期時間 Cache=cache.withExpiryPolicy(new CreateExpiryPolicy(new Duration(TimeUnit.Hours,24)))
Person類
public class Person implements Serializable {
/** Person ID (indexed). */
@QuerySqlField(index = true)
private long id;
/** Organization ID (indexed). 對此欄位新增索引*/
@QuerySqlField(index = true)
private long orgId;
/** First name (not-indexed). 不索引*/
@QuerySqlField
private String firstName;
/** Last name (not indexed). */
@QuerySqlField
private String lastName;
/** Resume text (create LUCENE-based TEXT index for this field). */
@QueryTextField
private String resume;
/** Salary (indexed). */
@QuerySqlField(index = true)
private double salary;
}
Person類的 @QuerySqlField屬性是必須的 推薦所有的欄位至少設定這個屬性 這樣可以使用sql的方式進行查詢否則沒有設定此屬性的列將不能進行查詢
Person是一個自定義類,定義快取時建議使用上面的程式碼方式首先建立一個 CacheConfiguration 配置類,配置相關的屬性後 ,例如上面再使用它的配置方式配置了快取的名字、儲存模式、快取的索引類,其中
cfg.setIndexedTypes(Integer.class, TestClass.class); 設定索引類這一配置是必須的 ,主要原因如下:
(重要) 通過建立類的形式進行快取的儲存,例如上面的例子就是(實際使用過程中大多數會使用這種形式),如果在查詢過程 中想以表的形式查詢(ignite提供了多種Sql的查詢方式),那麼必須使用這一句說明索引類。否則就只能以Key-value的方式讀取對應Key的資料,而不能使用其他的類似sql過濾的方式查詢資料
(重要)存入快取的類例如上面的Person類 如果想使用sql語句中條件過濾的方式查詢資料,請將類的欄位加上如上的註解
@QuerySqlField(index = true) 會給此欄位新增單獨的索引 @QuerySqlField 此欄位允許條件查詢
(重要) 如果希望以sql的語句查詢Person類 請不要再Person類中定義Map之類的複雜資料結構,否則將造成不能使用sql進行查詢
3 存入資料
//同步儲存
Cache.put(1, new Person(1,2)); //使用類的形式儲存快取資料
Cache.put(2, new Person(2,3));
//非同步儲存
Cache.putAsync(1, new Person(1,2)); //使用類的形式儲存快取資料
Cache.putAsync(2, new Person(2,3));
4 讀取資料
(1)以Key-Value的方式進行讀取
Student hello = Cache.get(1);
直接使用get函式讀取引數為key
(2)使用SqlQuery讀取(推薦使用此方式進行資料的查詢)
SqlQuery<Integer, Student> ss1=new SqlQuery(Student.class,"classId>0 and classId=1");
List<Entry<Integer, Student>> slist =stuCache.query(ss1).getAll();
SqlQuery 類的第二個引數 是sql組合的形式例如在例子中使用and進行了組合查詢
(3)使用SqlFieldsQuery進行資料查詢
SqlFieldsQuery query = new SqlFieldsQuery(
"select stu.classId,stu.name from Student as stu ");
List<List<?>> result= stuCache.query(query).getAll();
此種方式支援完整的sql語句,例如上面的表明是Student和儲存的類名是一致的,也可以使用cache.Student來進行限定,此種方式還支援多個表關聯查詢
例如 SqlFieldsQuery query = new SqlFieldsQuery(
"select stu.classId,stu.name from Student as stu,cache2.School where stu.classid=cache2.School.classid ");
(重要)此種方式注意中文亂碼,在測試過程中發現中文出現亂碼,使用多種編碼 格式沒有解決此問題
(4)使用java的SQI進行查詢
此種方式與標準的資料庫查詢是一樣的簡單易用,前提是按照開始建立資料庫的方式成功建立了表
try
{
Class.forName("org.apache.ignite.IgniteJdbcThinDriver");
} catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
// Open JDBC connection
Connection conn=null;;
try {
conn = DriverManager.getConnection("jdbc:ignite:thin://127.0.0.1/");
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// Get data
if(conn==null)
return;
try (Statement stmt = conn.createStatement()) {
try (ResultSet rs =
stmt.executeQuery("SELECT p.name, c.name " +
" FROM Person p, City c " +
" WHERE p.city_id = c.id")) {
while (rs.next())
System.out.println(rs.getString(1) + ", " + rs.getString(2));
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
5 可以使用DBeaver軟體檢視ignite快取成功建立的表
此軟體對ignite的支援不太完美,但可以檢視成功建了那些表
注意建立了快取並不代表可以以表的形式訪問了,需使用本文提到的方式建立快取才能以表的形式訪問
6 使用bin目錄下的 ignitevisorcmd.bat工具檢視快取
(1)開啟工具後輸入open連線ignite ,隨後根據出現的提示輸入配置檔案編號就可以
(2)輸入cache可以檢視當前建立的快取
(3) 使用cache的其他命令可以詳細檢視cache中的每一條資料