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中的每一条数据

   

    

  • 1
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
在使用 Ignite 作为 Spring Boot 应用程序的缓存解决方案时,可以使用 Spring Data 的注释来创建缓存表。以下是在 Spring Boot 中使用 Ignite 创建缓存表的简单步骤: 1. 首先,需要在 Spring Boot 应用程序中添加对 Apache Ignite 的依赖,可以在 pom.xml 文件中添加以下依赖: ``` <dependency> <groupId>org.apache.ignite</groupId> <artifactId>ignite-core</artifactId> <version>${ignite.version}</version> </dependency> <dependency> <groupId>org.apache.ignite</groupId> <artifactId>ignite-spring-data</artifactId> <version>${ignite.version}</version> </dependency> ``` 2. 创建一个缓存表实体类,可以使用 Spring Data 的 @Cacheable 和 @QuerySqlField 注释来标记实体类和字段: ``` @Cacheable public class Person { @QuerySqlField(index = true) private String name; @QuerySqlField private int age; // getters and setters } ``` 3. 创建一个缓存配置类,使用 IgniteConfiguration 和 CacheConfiguration 来配置缓存表: ``` @Configuration public class IgniteCacheConfig { @Bean public Ignite igniteInstance() { IgniteConfiguration cfg = new IgniteConfiguration(); // configure ignite instance return Ignition.start(cfg); } @Bean public CacheConfiguration<String, Person> personCacheConfig() { CacheConfiguration<String, Person> cacheCfg = new CacheConfiguration<>("personCache"); // configure cache return cacheCfg; } } ``` 4. 在需要使用缓存表的地方,可以使用 Spring Data 的 JpaRepository 接口来操作缓存表: ``` @Repository public interface PersonRepository extends JpaRepository<Person, String> { } ``` 通过以上步骤,就可以在 Spring Boot 应用程序中使用 Ignite 创建缓存表了。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值