1. 程式人生 > >Redis的安裝過程及與SSM結合使用

Redis的安裝過程及與SSM結合使用

Redis安裝過程

  1. 下載安裝包,解壓,Mac系統將資料夾放在/usr/local資料夾下

  2. 開啟終端,先安裝伺服器端server
    終端$ cd /usr/local/redis/

  3. 去檔案下進入redis.config檔案
    這裡寫圖片描述
    找到requirepass刪除前面的#
    並修改後面拼接的密碼
    儲存

  4. 進入終端
    輸入命令
    終端$ cd src/
    終端$ ./redis-server ../redis.conf
    進入redis的伺服器端
    Ctrl + c退出

(如果在過程中提示沒有許可權就在命令前加sudo)

但在使用的過程中不要退出

  1. 再開啟一個終端,安裝客戶端試用
    命令
    終端$ cd /usr/local/redis/src/

    終端$ ./redis-cli -a 密碼
    就進入到了redis的客戶端

操作redis客戶端的命令
* 這裡寫圖片描述
前面的是ip地址:埠號
keys * 查詢所有的key
* 這裡寫圖片描述
設定key和value
* get name
通過key獲取value
* flushdb
清除redis記憶體中的資料,但不建議經常使用,影響伺服器的效能
* del name
也可以通過key刪除資料
* exit
退出

redis和SSM結合使用

1.搭建一個SSM的專案,並連線資料庫
下面我主要介紹和redis有關的配置
2.建立RedisCache類,這個類是redis的核心

package com.dhl.redis;
// redis快取
// jedis redis for Java

/**
 * 序列化的是資料
 * 不會序列化類結構
 * 但會序列化關係(資料對應的類結構)
 */

public class RedisCache implements Cache {
    // 基於Redis的MyBatis二級快取的實現

    // 需要中間類對其進行靜態注
    private static JedisConnectionFactory jedisConnectionFactory;

    private final String id;

    private
final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) { RedisCache.jedisConnectionFactory = jedisConnectionFactory; } // 根據標識構造快取物件 public RedisCache(String id) { if (id == null){ // 丟擲非法引數異常 throw new IllegalArgumentException("快取id不能為空"); } this.id = id; } /** * 獲取快取物件的唯一標準 * * @return */ public String getId() { return this.id; } /** * 把key/value儲存到快取物件中 */ public void putObject(Object key, Object value) { JedisConnection jedisConnection = null; try { //操作readis進行儲存 jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection(); //建立一個序列化工具 RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer(); // 建立連線,儲存key的value jedisConnection.set(serializer.serialize(key),serializer.serialize(value)); }catch (JedisConnectionException e){ e.printStackTrace(); }finally { if (jedisConnection != null){ jedisConnection.close(); } } } public Object getObject(Object key) { // 通過key從快取物件中獲取value Object result = null; JedisConnection jedisConnection = null; try { // 建立連線 jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection(); RedisSerializer<Object> serializer= new JdkSerializationRedisSerializer(); byte[] bytes = jedisConnection.get(serializer.serialize(key)); // 1. 將key序列化 // 2. 通過connection獲取序列化的value // 3. 將序列化的value反序列化 result = serializer.deserialize(bytes); /** * 序列化的是資料 * 不會序列化類結構 * 但會序列化關係(資料對應的類結構) */ }catch (JedisConnectionException e){ e.printStackTrace(); }finally { if (jedisConnection != null){ jedisConnection.close(); } } return result; } /** * 不是需要實現的方法,沒有被核心框架呼叫 * 方法作用: 根據key移除對應的value */ public Object removeObject(Object key) { Object result = null; JedisConnection jedisConnection = null; try { // 建立連線 jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection(); RedisSerializer<Object> serializer= new JdkSerializationRedisSerializer(); // 移除儲存到的值 result = jedisConnection.expire(serializer.serialize(key),0); }catch (JedisConnectionException e){ e.printStackTrace(); }finally { if (jedisConnection != null){ jedisConnection.close(); } } return result; } // 清除快取(操作影響效能,效率低,不建議經常清除) public void clear() { JedisConnection jedisConnection = null; try { jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection(); // 清除快取 jedisConnection.flushDb(); // 清除設定 jedisConnection.flushAll(); }catch (JedisConnectionException e){ }finally { if (jedisConnection != null){ jedisConnection.close(); } } } /** * 獲取快取物件中存取的key/value的數量 * @return */ public int getSize() { Integer count = 0; JedisConnection jedisConnection = null; try { jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection(); count = Integer.valueOf(jedisConnection.dbSize().toString()); }catch (JedisConnectionException e){ }finally { if (jedisConnection != null){ jedisConnection.close(); } } return count; } // 獲取讀寫鎖 // 從mybatis的3.2.6版本,這個方法不再被框架核心呼叫 // 所有需要的鎖,都必須由快取供應商來提供 public ReadWriteLock getReadWriteLock() { return this.readWriteLock; } }

3.建立中間類

package com.lanou.redis;

public class RedisCacheTransfer {

    @Autowired
    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory){
        RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
    }
}

4.redis的配置檔案—-(1)redis.properties

# Redis的配置
redis.host=127.0.0.1
redis.port=6379
redis.pass=111111

redis.maxIdl=300
redis.maxActive=600
redis.maxWait=1000

5.redis的配置檔案—-(2)SSM-redis.xml
這個配置檔案也可以和SSM-mybatis.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:redis.properties</value>
                <value>classpath:db.properties</value>
            </list>
        </property>
    </bean>

    <!--構建redis的資料來源-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdl}"/>
        <property name="maxTotal" value="${redis.maxActive}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
    </bean>

    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:hostName="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:poolConfig-ref="poolConfig"
    />

    <bean id="redisCacheTranfer" class="com.lanou.redis.RedisCacheTransfer">
        <property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
    </bean>


</beans>

6.mybatis的配置檔案—–mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>

        <!--查詢的時候,關閉關聯物件即使載入,為了提高效能-->
        <setting name="lazyLoadingEnabled" value="false"/>

        <!--允許多個結果集,預設就是true-->
        <setting name="multipleResultSetsEnabled" value="true"/>

        <!--設定關聯的物件載入的形態,此處是按需載入欄位.不會載入所有的欄位,而是有sql來決定-->
        <setting name="aggressiveLazyLoading" value="true"/>


    </settings>

    <!-- Continue going here -->

</configuration>

7.最後不要忘記在web.xml的配置檔案中配置SSM-redis.xml

8.可以寫查詢語句進行測試,執行成功之後我們可以去進入終端,使用redis的客戶端,通過key * 可以查到記憶體中的資料

Redis安裝過程

  1. 下載安裝包,解壓,Mac系統將資料夾放在/usr/local資料夾下

  2. 開啟終端,先安裝伺服器端server
    終端$ cd /usr/local/redis/

  3. 去檔案下進入redis.config檔案

    找到requirepass刪除前面的#
    並修改後面拼接的密碼
    儲存

  4. 進入終端
    輸入命令
    終端$ cd src/
    終端$ ./redis-server ../redis.conf
    進入redis的伺服器端
    Ctrl + c退出

(如果在過程中提示沒有許可權就在命令前加sudo)

但在使用的過程中不要退出

  1. 再開啟一個終端,安裝客戶端試用
    命令
    終端cd/usr/local/redis/src/ ./redis-cli -a 密碼
    就進入到了redis的客戶端

操作redis客戶端的命令
*
前面的是ip地址:埠號
keys * 查詢所有的key
*
設定key和value
*
通過key獲取value
*
清除redis記憶體中的資料,但不建議經常使用,影響伺服器的效能
*
也可以通過key刪除資料
*
退出

redis和SSM結合使用

1.搭建一個SSM的專案,並連線資料庫
下面我主要介紹和redis有關的配置
2.建立RedisCache類,這個類是redis的核心

package com.dhl.redis;
// redis快取
// jedis redis for Java

/**
 * 序列化的是資料
 * 不會序列化類結構
 * 但會序列化關係(資料對應的類結構)
 */

public class RedisCache implements Cache {
    // 基於Redis的MyBatis二級快取的實現

    // 需要中間類對其進行靜態注
    private static JedisConnectionFactory jedisConnectionFactory;

    private final String id;

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();


    public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
        RedisCache.jedisConnectionFactory = jedisConnectionFactory;
    }

    // 根據標識構造快取物件
    public RedisCache(String id) {
        if (id == null){
            // 丟擲非法引數異常
            throw new IllegalArgumentException("快取id不能為空");
        }
        this.id = id;
    }
    /**
     * 獲取快取物件的唯一標準
     *
     * @return
     */
    public String getId() {
        return this.id;
    }
    /**
     * 把key/value儲存到快取物件中
     */
    public void putObject(Object key, Object value) {

        JedisConnection jedisConnection = null;
        try {
            //操作readis進行儲存
            jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection();


            //建立一個序列化工具
            RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();

            // 建立連線,儲存key的value
            jedisConnection.set(serializer.serialize(key),serializer.serialize(value));
        }catch (JedisConnectionException e){
            e.printStackTrace();
        }finally {
            if (jedisConnection != null){
                jedisConnection.close();
            }
        }

    }

    public Object getObject(Object key) {
        // 通過key從快取物件中獲取value

        Object result = null;
        JedisConnection jedisConnection = null;
        try {
            // 建立連線
            jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection();

            RedisSerializer<Object> serializer= new JdkSerializationRedisSerializer();

            byte[] bytes = jedisConnection.get(serializer.serialize(key));

            // 1. 將key序列化
            // 2. 通過connection獲取序列化的value
            // 3. 將序列化的value反序列化

            result = serializer.deserialize(bytes);


            /**
             * 序列化的是資料
             * 不會序列化類結構
             * 但會序列化關係(資料對應的類結構)
             */


        }catch (JedisConnectionException e){
            e.printStackTrace();
        }finally {
            if (jedisConnection != null){
                jedisConnection.close();
            }
        }
        return result;
    }

    /**
     * 不是需要實現的方法,沒有被核心框架呼叫
     * 方法作用: 根據key移除對應的value
     */
    public Object removeObject(Object key) {

        Object result = null;
        JedisConnection jedisConnection = null;
        try {
            // 建立連線
            jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection();

            RedisSerializer<Object> serializer= new JdkSerializationRedisSerializer();

            // 移除儲存到的值
            result = jedisConnection.expire(serializer.serialize(key),0);

        }catch (JedisConnectionException e){
            e.printStackTrace();
        }finally {
            if (jedisConnection != null){
                jedisConnection.close();
            }
        }
        return result;
    }

    // 清除快取(操作影響效能,效率低,不建議經常清除)
    public void clear() {
        JedisConnection jedisConnection = null;
        try {
            jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection();
            // 清除快取
            jedisConnection.flushDb();
            // 清除設定
            jedisConnection.flushAll();

        }catch (JedisConnectionException e){

        }finally {
            if (jedisConnection != null){
                jedisConnection.close();
            }
        }
    }

    /**
     * 獲取快取物件中存取的key/value的數量
     * @return
     */
    public int getSize() {
        Integer count = 0;
        JedisConnection jedisConnection = null;
        try {
            jedisConnection = (JedisConnection) jedisConnectionFactory.getConnection();

            count = Integer.valueOf(jedisConnection.dbSize().toString());

        }catch (JedisConnectionException e){

        }finally {
            if (jedisConnection != null){
                jedisConnection.close();
            }
        }
        return count;
    }

    // 獲取讀寫鎖
    // 從mybatis的3.2.6版本,這個方法不再被框架核心呼叫
    // 所有需要的鎖,都必須由快取供應商來提供
    public ReadWriteLock getReadWriteLock() {
        return this.readWriteLock;
    }
}

3.建立中間類

package com.lanou.redis;

public class RedisCacheTransfer {

    @Autowired
    public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory){
        RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
    }
}

4.redis的配置檔案—-(1)redis.properties

# Redis的配置
redis.host=127.0.0.1
redis.port=6379
redis.pass=111111

redis.maxIdl=300
redis.maxActive=600
redis.maxWait=1000

5.redis的配置檔案—-(2)SSM-redis.xml
這個配置檔案也可以和SSM-mybatis.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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:redis.properties</value>
                <value>classpath:db.properties</value>
            </list>
        </property>
    </bean>

    <!--構建redis的資料來源-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdl}"/>
        <property name="maxTotal" value="${redis.maxActive}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
    </bean>

    <bean id="jedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:hostName="${redis.host}" p:port="${redis.port}" p:password="${redis.pass}" p:poolConfig-ref="poolConfig"
    />

    <bean id="redisCacheTranfer" class="com.lanou.redis.RedisCacheTransfer">
        <property name="jedisConnectionFactory" ref="jedisConnectionFactory"/>
    </bean>


</beans>

6.mybatis的配置檔案—–mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait for a response from the database -->
        <setting name="defaultStatementTimeout" value="3000"/>
        <!-- Enables automatic mapping from classic database column names A_COLUMN to camel case classic Java property names aColumn -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!-- Allows JDBC support for generated keys. A compatible driver is required.
        This setting forces generated keys to be used if set to true,
         as some drivers deny compatibility but still work -->
        <setting name="useGeneratedKeys" value="true"/>

        <!--查詢的時候,關閉關聯物件即使載入,為了提高效能-->
        <setting name="lazyLoadingEnabled" value="false"/>

        <!--允許多個結果集,預設就是true-->
        <setting name="multipleResultSetsEnabled" value="true"/>

        <!--設定關聯的物件載入的形態,此處是按需載入欄位.不會載入所有的欄位,而是有sql來決定-->
        <setting name="aggressiveLazyLoading" value="true"/>


    </settings>

    <!-- Continue going here -->

</configuration>

7.最後不要忘記在web.xml的配置檔案中配置SSM-redis.xml

8.可以寫查詢語句進行測試,執行成功之後我們可以去進入終端,使用redis的客戶端,通過key * 可以查到記憶體中的資料