《Spring實戰》-第十二章:Spring與NoSQL

慢來比較快,虛心學技術

隨着非關係型數據庫(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]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章