美文网首页Java 杂谈JAVA学习记录Java
《Spring实战》-第十二章:Spring与NoSQL

《Spring实战》-第十二章:Spring与NoSQL

作者: 廖小明的赖胖子 | 来源:发表于2019-04-02 23:30 被阅读0次

    慢来比较快,虚心学技术

    随着非关系型数据库(NoSQL数据库)概念的流行,Spring也开始提供非关系型数据库的支持,Spring主要提供以下几种非关系型数据库的支持:

    • MongoDB -----文档数据库,不是通用的数据库,它们所擅长解决的是一个很小的问题集
    • Neo4j -----------图数据库。
    • Redis -----------键值对数据库

    现如今用的比较多的NoSQL数据库是Redis数据库,我们以Spring整合Redis数据库为例了解Spring对NoSQL的支持

    一、Spring Data Redis体系结构分析

    Spring-data-redis提供了在srping应用中通过简单的配置访问redis服务,对reids底层开发包(Jedis, JRedis, and RJC)进行了高度封装,RedisTemplate提供了redis各种操作、异常处理及序列化,支持发布订阅,并对spring 3.1 cache进行了实现。

    • 连接到 Redis

    Redis 连接工厂会生成到 Redis 数据库服务器的连接。 Spring Data Redis 为四种 Redis 客户端实现提供了连接工厂:

    • JedisConnectionFactory----------最为常用

    • SrpConnectionFactory

    • LettuceConnectionFactory

    • JredisConnectionFactory

    • 操作Redis

    RedisTemplate对应不同需求封装了如下操作:

    opsForValue()------普通键值对操作
    opsForList()---------ArrayList键值对操作
    opsForSet()---------HashSet键值对操作
    opsForHash()------HashMap键值对操作

    二、Spring 整合使用Spring Data Redis

    ①引入依赖

    <!--引入Spring Data Redis-->
    <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-redis -->
    <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-redis</artifactId>
        <version>2.1.5.RELEASE</version>
    </dependency>
    
    <!--引入jedis支持-->
    <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
    <dependency>
        <groupId>redis.clients</groupId>
        <artifactId>jedis</artifactId>
        <version>2.9.1</version>
    </dependency>
    

    ②编写redis配置文件:redis.properties

    #redis地址
    redis.host=127.0.0.1
    #redis端口
    redis.port=6379
    #redis密码,一般不需要
    redis.password=""
    #最大空闲时间
    redis.maxIdle=400
    #最大连接数
    redis.maxTotal=6000
    #最大等待时间
    redis.maxWaitMillis=1000
    #连接耗尽时是否阻塞,false报异常,true阻塞超时 默认:true
    redis.blockWhenExhausted=true
    #在获得链接的时候检查有效性,默认false
    redis.testOnBorrow=true
    #超时时间,默认:2000
    redis.timeout=100000
    

    ③编写Spring配置文件并配置Redis:application.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans.xsd 
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context.xsd 
           http://www.springframework.org/schema/tx 
           http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!--开启注解扫描-->
        <context:annotation-config/>
        <!--指定组件扫描范围-->
        <context:component-scan base-package="com.my.spring"/>
    
        <!--引入redis资源文件-->
        <context:property-placeholder location="classpath*:redis.properties"/>
    
        <!-- redis数据源 -->
        <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
            <!-- 最大空闲数 -->
            <property name="maxIdle" value="${redis.maxIdle}" />
            <!-- 最大空连接数 -->
            <property name="maxTotal" value="${redis.maxTotal}" />
            <!-- 最大等待时间 -->
            <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
            <!-- 连接超时时是否阻塞,false时报异常,ture阻塞直到超时, 默认true -->
            <property name="blockWhenExhausted" value="${redis.blockWhenExhausted}" />
            <!-- 返回连接时,检测连接是否成功 -->
            <property name="testOnBorrow" value="${redis.testOnBorrow}" />
        </bean>
    
        <!-- Spring-redis连接池管理工厂 -->
        <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
            <!-- IP地址 -->
            <property name="hostName" value="${redis.host}" />
            <!-- 端口号 -->
           <property name="port" value="${redis.port}" />
            <!-- 超时时间 默认2000-->
            <property name="timeout" value="${redis.timeout}" />
            <!-- 连接池配置引用 -->
            <property name="poolConfig" ref="poolConfig" />
            <!-- usePool:是否使用连接池 -->
            <property name="usePool" value="true"/>
        </bean>
    
        <!-- 注册RedisTemplate -->
        <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
            <!--注入连接池管理工具-->
            <property name="connectionFactory" ref="jedisConnectionFactory" />
            <!--设置Redis的key序列化方式-->
            <property name="keySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
            </property>
            <!--设置Redis的value序列化方式-->
            <property name="valueSerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
            </property>
            <!--设置Redis存入haseMap时的key序列化方式-->
            <property name="hashKeySerializer">
                <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
            </property>
            <!--设置Redis存入haseMap时的value序列化方式-->
            <property name="hashValueSerializer">
                <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
            </property>
            <!--开启事务  -->
            <property name="enableTransactionSupport" value="true"></property>
        </bean>
    
        <!--自定义redis工具类  -->
        <bean id="redisHelper" class="com.my.spring.util.RedisHelper">
            <property name="redisTemplate" ref="redisTemplate" />
        </bean>
    </beans>
    

    ④编写Redis工具类:RedisManager,注入RedisTemplate

    @Data
    public class RedisHelper {
    
        //注入RedisTemplate
        private RedisTemplate<String,Object> redisTemplate;
    
        /**
         * 设置过期时间
         * @param key
         * @param time
         * @return
         */
        public boolean expire(String key, long time) {
            return this.redisTemplate.expire(key,time, TimeUnit.SECONDS);
        }
    
         /**
         * 是否存在key
         * @param key
         * @return
         */
        public Object hasKey(String key){
            return this.redisTemplate.hasKey(key);
        }
    
        /**
         * 获取过期时间
         * @param key
         * @return
         */
        public long getExpire(String key){
            return this.redisTemplate.getExpire(key);
        }
    
        /**
         * 根据key获取值
         * @param key
         * @return
         */
        public Object get(String key){
            Object o = redisTemplate.opsForValue().get(key);
            return o;
        }
    
        /**
         * 存储key-value
         * @param key
         * @param value
         * @return
         */
        public boolean set(String key,Object value){
            redisTemplate.opsForValue().set(key,value);
            return true;
        }
    
        /**
         * 存入key-value并设置过期时间,以秒为单位
         * @param key
         * @param value
         * @param time
         * @return
         */
        public boolean set(String key,Object value,long time){
            redisTemplate.opsForValue().set(key,value,time,TimeUnit.SECONDS);
            return true;
        }
    
        /**
         * 将值以set形式存入redis中
         * @param key
         * @param values
         * @return
         */
        public long sSet(String key,Object ...values){
            return this.redisTemplate.opsForSet().add(key,values);
        }
    
        /**
         * 获取键为key的set
         * @param key
         * @return
         */
        public Set<String> sGet(String key){
            return this.redisTemplate.opsForSet().members(key);
        }
    
    }
    

    ⑤编写测试类

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {"classpath:application.xml"})
    public class AppTest {
    
        @Autowired
        private RedisHelper redisHelper;
    
        @Test
        public void testSet(){
           this.redisHelper.set("testKey","testValue")
        }
    
       @Test
        public void testGet(){
            System.out.println(this.redisHelper.get("testKey"));
        }
    
        @Test
        public void testsSet(){
           this.redisHelper.sSet("testKey2","testValue1","testValue2","testValue3")
        }
    
        @Test
        public void testsGet(){
            Set<String> set = this.redisHelper.sGet("testKey2");
            System.out.println(set.toString());
        }
    }
    

    运行测试,测试结果:

    运行testSet():


    运行testGet():

    testValue
    

    运行testsSet():

    运行testsGet():

    [testValue1, testValue3, testValue2]
    

    相关文章

      网友评论

        本文标题:《Spring实战》-第十二章:Spring与NoSQL

        本文链接:https://www.haomeiwen.com/subject/yglobqtx.html