Ignite 的使用过程(一)
下载安装与运行
- 进入https://ignite.apache.org/download.cgi#binaries 下载编译完成后的文件
- 解压完成后进入与bin的同级目录下执行 .\bin\ignite.bat .\examples\config\example-cache.xml
出现 ^– default [initSize=256.0 MiB, maxSize=1.6 GiB, persistenceEnabled=false]表示运行成功
注意,我因为jdk的问题导致运行脚本出现内存溢出的问题,一定要选择对正确的jdk与版本(我使用的是jdk8 64位)
程序中使用
- 下载所需要的jar包
ignite-core-2.4.0.jar(在下载的ignite包中的libs目录下)
ignite-spring-2.4.0.jar
spring-aop-4.3.7.RELEASE.jar
ignite-indexing-2.4.0.jar
ignite-spring-2.4.0.jar
cache-api-1.0.0.jar 代码:
Ignition.setClientMode(true);//这句表示此链接是一个客户端 Ignition.start("ignite/example-cache.xml");//文件与启动ignite的xml相同 Ignite ignite = Ignition.ignite();//获取一个ignite实例
获取要进行操作的缓存对象:
CacheConfiguration<Integer, Person> cacheOnlyPersonCfg = new CacheConfiguration<Integer, Person>("personCache");//动态创建名为personCache的缓存,也可以使用ignite.cache("personCache")来获取,前提是已经创建过 cacheOnlyPersonCfg.setIndexedTypes(Integer.class, Person.class); // 注意配置注册key和value是为了sql查询 // Get an instance of named cache. final IgniteCache<Integer, Person> cache = ignite.getOrCreateCache(cacheOnlyPersonCfg);//"personCache"); //获取一个IgniteCache实例
开始进行存取操作
for (int i = 0; i < 3; i++) { Person ps = new Person(); ps.setId(i); ps.setName("小明"); cache.put(i, ps); } Person ps = new Person(); ps.setId(5); ps.setName("小明"); SqlFieldsQuery qqq = new SqlFieldsQuery("INSERT INTO person(_key, _val) VALUES(?, ?)"); qqq.setArgs(111L, ps); cache.query(qqq); SqlFieldsQuery sql2 = new SqlFieldsQuery("update person set name = ? where id = ?"); cache.query(sql2.setArgs("小明123", 1)).getAll(); SqlQuery<Integer, Person> sql = new SqlQuery(Person.class, "1=1"); List<Cache.Entry<Integer, Person>> cursor = cache.query(sql).getAll(); if (cursor != null) { for (Cache.Entry<Integer, Person> p : cursor) { System.out.println(p.getValue().getName()); } }
可以看出ignite可以适用对象来直接操作,也可以使用sql来操作
Person.class
public class Person { @QuerySqlField(index=true) private int id; @QuerySqlField private String name; @QuerySqlField private int city_id; /** * @return the id */ public int getId() { return id; } /** * @param id the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the city_id */ public int getCity_id() { return city_id; } /** * @param city_id the city_id to set */ public void setCity_id(int city_id) { this.city_id = city_id; }