1. 程式人生 > >2.ssm+redis快取配置

2.ssm+redis快取配置

1、pom.xml引入一下jar

	<!-- spring-redis實現 -->
	<dependency>
	    <groupId>org.springframework.data</groupId>
	    <artifactId>spring-data-redis</artifactId>
	    <version>1.6.2.RELEASE</version>
	</dependency>
	<!-- redis客戶端jar -->
	<dependency>
	    <groupId>redis.clients</groupId>
	    <artifactId>jedis</artifactId>
	    <version>2.8.0</version>
	</dependency>
	<!-- Ehcache實現,用於參考 -->
	<dependency>
	    <groupId>org.mybatis</groupId>
	    <artifactId>mybatis-ehcache</artifactId>
	    <version>1.0.0</version>
	</dependency>

2、application-context.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:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
						http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
						http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
						http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
						http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
						
	<!-- 使用annotation 自動註冊bean,並保證@Required,@Autowired的屬性被注入 -->
	<context:component-scan base-package="com.langcheng.**"/>
	<!--<bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>  -->
	<!-- redis配置 -->
        <!-- redis連線池 -->  
   	<bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">   
       	<property name="maxIdle" value="10" />
		<property name="maxTotal" value="105" />
		<property name="maxWaitMillis" value="5000" />
		<property name="testOnBorrow" value="true" />
   	</bean>  
   	<!-- redis連線工廠 -->  
   	<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
       	<property name="hostName" value="127.0.0.1"></property>  
       	<property name="port" value="6379"></property>  
       	<property name="password" value=""></property>  
       	<property name="poolConfig" ref="jedisConfig"></property>  
   	</bean>  
   	
        <!-- redis操作模板,這裡採用儘量面向物件的模板 -->  
   	<bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
       	<property name="connectionFactory" ref="connectionFactory" />  
   		<!-- 如果不配置Serializer,那麼儲存的時候只能使用String,如果用物件型別儲存,那麼會提示錯誤 can't cast to String!!! 
       	<property name="keySerializer">  
           	<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
       	</property>  
       	<property name="valueSerializer">  
           	<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  
      	</property>  
       
    	<property name="hashKeySerializer">  
        	<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
    	</property>  
    	<property name="hashValueSerializer">  
        	<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
    	</property>  --> 
   	</bean>  
   	
   	<!-- redis服務封裝
   	<bean id="redisService" class="com.langcheng.redis.impl.RedisServiceImpl">
	</bean>  -->
</beans>

3、springmvc-Servlet.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"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:util="http://www.springframework.org/schema/util"  
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
				http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
				http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
				http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
				http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
				http://www.springframework.org/schema/util        
                http://www.springframework.org/schema/util/spring-util-3.2.xsd ">

	<!-- 自動註冊 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	<!-- 掃描控制器 -->
	<context:component-scan base-package="com.langcheng.controller" />
	<!-- 掃描邏輯層 
	<context:component-scan base-package="com.langcheng.redis" />-->
	
	 <!--<context:component-scan base-package="com.langcheng.controller">
       不再管理Controller 註解  因為它單獨給mvc-servler.xml去管理
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
        </context:component-scan>-->
	
	<!-- <context:component-scan base-package="com.langcheng.aop.api"></context:component-scan>-->
	
	<!-- jdk動態代理織入增強 @aspectJ切面的bean建立代理,織入切面 -->
	<aop:aspectj-autoproxy expose-proxy="false" />
	<tx:annotation-driven transaction-manager="transactionManager" order="2"/>
	
	<!-- 靜態資源訪問 -->
	<mvc:resources location="/resource/" mapping="/resource/**" />
	<mvc:resources location="/intercity/" mapping="/intercity/**" />
	<mvc:resources location="/ownersection/" mapping="/ownersection/**" />
	<mvc:resources location="/" mapping="/**/*.html" />
 	
 
	<!--- StringHttpMessageConverter bean -->
	<bean id="stringHttpMessageConverter"  
        class="org.springframework.http.converter.StringHttpMessageConverter">  
        <constructor-arg value="UTF-8" index="0"></constructor-arg><!--  
              避免出現亂碼 -->  
        <property name="supportedMediaTypes">  
            <list>  
                <value>text/plain;charset=UTF-8</value>  
            </list>  
        </property>  
    </bean> 

	<!-- 啟動Spring MVC的註解功能,完成請求和註解POJO的對映 -->
	<bean
		class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters">
			<list>
				<ref bean="stringHttpMessageConverter" />
			</list>
		</property>
	</bean>

	<!-- 檢視解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass">
			<value>org.springframework.web.servlet.view.JstlView</value>
		</property>
		<property name="prefix">
			<value>/WEB-INF/page/</value>
		</property>
		<property name="suffix">
			<value>.jsp</value>
		</property>
	</bean>

	<!-- Session失效攔截
  	<mvc:interceptors>  -->
    	<!-- 定義攔截器 
     	<mvc:interceptor> -->
        <!-- 匹配的是url路徑, 如果不配置或/**,將攔截所有的Controller
        <mvc:mapping path="/**" />  
        <mvc:exclude-mapping path="/**/fonts/*"/>
        <mvc:exclude-mapping path="/**/*.css"/>
        <mvc:exclude-mapping path="/**/*.js"/>
        <mvc:exclude-mapping path="/**/**/*.js"/>
        <mvc:exclude-mapping path="/**/*.png"/>
        <mvc:exclude-mapping path="/**/*.gif"/>
        <mvc:exclude-mapping path="/**/*.jpg"/>
        <mvc:exclude-mapping path="/**/*.jpeg"/>
        <mvc:exclude-mapping path="/**/*login*"/>
        <mvc:exclude-mapping path="/**/*findUser*"/>  -->
        <!-- 不用攔截的路徑
        <bean class="com.langcheng.interceptor.LoginInterceptor"></bean> 
    	</mvc:interceptor> 
  	</mvc:interceptors> --> 
  	
  	<!-- ajaxSession失效過濾
  	<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
		<property name="interceptors">
            <list>
            </list>
        </property>
	</bean> -->
  	
	<!-- 上傳檔案 -->
	<bean id="multipartResolver"
		class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="utf-8" />
		<!-- 最大記憶體大小 -->
		<property name="maxInMemorySize" value="10240" />
		<!-- 最大檔案大小,-1為不限制大小 -->
		<property name="maxUploadSize" value="-1" />
	</bean>

</beans>


4、編寫redis服務端用於測試

1.編寫RedisService.java

package com.langcheng.redis.api;

import java.util.Set;

/**
 * 封裝redis 快取伺服器服務介面
 * @author doop
 *@version 1.0 測試版,聯絡使用
 */
public interface RedisService {

    /**
     * 通過key刪除(位元組)
     * @param key
     */
    public void del(byte [] key);
	 
    /**
     * 通過key刪除
     * @param key
     */
    public void del(String key);
	 
    /**
     * 新增key value 並且設定存活時間(byte)
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(byte [] key,byte [] value,int liveTime);
	 
    /**
     * 新增key value 並且設定存活時間
     * @param key
     * @param value
     * @param liveTime
     */
     public void set(String key,String value,int liveTime);
     
     /**
      * 新增key value
      * @param key
      * @param value
      */
     public void set(String key,String value);
     
     /**新增key value (位元組)(序列化)
      * @param key
      * @param value
      */
     public void set(byte [] key,byte [] value);
     
     /**
      * 獲取redis value (String)
      * @param key
      * @return
      */
     public String get(String key);
     
     /**
      * 獲取redis value (byte [] )(反序列化)
      * @param key
      * @return
      */
     public byte[] get(byte [] key);
     
     /**
      * 通過正則匹配keys
      * @param pattern
      * @return
      */
     public Set<String> keys(String pattern);
     
     /**
      * 檢查key是否已經存在
      * @param key
      * @return
      */
     public boolean exists(String key);
     
     /**
      * 清空redis 所有資料
      * @return
      */
     public String flushDB();
     
     /**
      * 檢視redis裡有多少資料
      */
     public long dbSize();
     
     /**
      * 檢查是否連線成功
      * @return
      */
     public String ping();
}

2.編寫RedisServiceImpl

package com.langcheng.redis.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Service;

import redis.clients.jedis.Jedis;

import com.langcheng.redis.api.RedisService;
@Service
public class RedisServiceImpl implements RedisService{
    //操作redis客戶端
    private static Jedis jedis;
    @Autowired
    private JedisConnectionFactory redisTemplate;
	    
    private  RedisServiceImpl (){
    }

	@Override
	public void del(byte[] key) {
		// TODO Auto-generated method stub
		this.getJedis().del(key);
	}

	@Override
	public void del(String key) {
		// TODO Auto-generated method stub
		this.getJedis().del(key);
	}

	@Override
	public void set(byte[] key, byte[] value, int liveTime) {
		// TODO Auto-generated method stub
		this.set(key, value);
        this.getJedis().expire(key, liveTime);
	}

	@Override
	public void set(String key, String value, int liveTime) {
		// TODO Auto-generated method stub
		 this.set(key, value);
	     this.getJedis().expire(key, liveTime);
	}

	@Override
	public void set(String key, String value) {
		// TODO Auto-generated method stub
		 this.getJedis().set(key, value);
	}

	@Override
	public void set(byte[] key, byte[] value) {
		// TODO Auto-generated method stub
		 this.getJedis().set(key, value);
	}

	@Override
	public String get(String key) {
		// TODO Auto-generated method stub
		String value = this.getJedis().get(key);
        return value;
	}

	@Override
	public byte[] get(byte[] key) {
		// TODO Auto-generated method stub
		return this.getJedis().get(key);
	}

	@Override
	public Set<String> keys(String pattern) {
		// TODO Auto-generated method stub
		return this.getJedis().keys(pattern);
	}

	@Override
	public boolean exists(String key) {
		// TODO Auto-generated method stub
		return this.getJedis().exists(key);
	}

	@Override
	public String flushDB() {
		// TODO Auto-generated method stub
		return this.getJedis().flushDB();
	}

	@Override
	public long dbSize() {
		// TODO Auto-generated method stub
		return this.getJedis().dbSize();
	}

	@Override
	public String ping() {
		// TODO Auto-generated method stub
		return this.getJedis().ping();
	}
	
	/**
     * 獲取一個jedis 客戶端
     * @return
     */
    private Jedis getJedis(){
        if(jedis == null){
            return redisTemplate.getShardInfo().createResource();
        }
        return jedis;
    }
}

3.編寫測試控制器

package com.langcheng.controller;


import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.langcheng.redis.api.RedisService;


@Controller
@RequestMapping(value = "/api")
public class RedisController {
	
	@Autowired
	private RedisService redisService;
	
	@RequestMapping(value = "/test")
	public void  test1() {
		String ping = redisService.ping();//測試是否連線成功,連線成功輸出PONG
        System.out.println(ping);

        //首先,我們看下redis服務裡是否有資料
        long dbSizeStart = redisService.dbSize();
        System.out.println(dbSizeStart);

        redisService.set("username", "oyhk");//設值(查看了原始碼,預設存活時間30分鐘)
        String username = redisService.get("username");//取值 
        System.out.println(username);
        redisService.set("username1", "oyhk1", 1);//設值,並且設定資料的存活時間(這裡以秒為單位)
        String username1 = redisService.get("username1");
        System.out.println(username1);
        try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}//我睡眠一會,再去取,這個時間超過了,他的存活時間
        String liveUsername1 = redisService.get("username1");
        System.out.println(liveUsername1);//輸出null

        //是否存在
        boolean exist = redisService.exists("username");
        System.out.println(exist);

        //檢視keys
        Set<String> keys = redisService.keys("*");//這裡檢視所有的keys
        System.out.println(keys);//只有username username1(已經清空了)

        //刪除
        redisService.set("username2", "oyhk2");
        String username2 = redisService.get("username2");
        System.out.println(username2);
        redisService.del("username2");
        String username2_2 = redisService.get("username2");
        System.out.println(username2_2);//如果為null,那麼就是刪除資料了

        //dbsize
        long dbSizeEnd = redisService.dbSize();
        System.out.println(dbSizeEnd);

        //清空reids所有資料
        //redisService.flushDB();
	}
	
	
}

進行測試輸出結果: