springmvc整合redis架构搭建实例

springmvc整合redis架构搭建实例
好久没学习了,因为自己公司主要做ERP系统,我主要负责这些产品的的开发工作,最近面试遇到了一些开发人员使用redis缓存用于web开发,因为自己没用过,也不是很了解就顺便解了一下,顺便在公司已有项目中测试整合redis,具体配置代码在下面贴出:


1.配置文件


 2.使用redis64位下载地址:

   http://download.csdn.net/download/xmt1139057136/9220075


第一步 : 创建 maven 项目 :


1.在已有pom.xml中引入jedis和spring-data-redis架包:

     <!-- redis集成 -->
        <dependency>
		  <groupId>redis.clients</groupId>
		  <artifactId>jedis</artifactId>
		  <version>2.9.0</version>
		</dependency>
		<dependency>  
            <groupId>org.springframework.data</groupId>  
            <artifactId>spring-data-redis</artifactId>  
            <version>1.6.2.RELEASE</version>  
        </dependency>  
        <!-- redis集成 -->

 
2.spring.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:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context" 
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd 
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.1.xsd 
            http://www.springframework.org/schema/aop 
            http://www.springframework.org/schema/aop/spring-aop-4.1.xsd 
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.1.xsd">

	<!-- 扫描service、dao组件 -->
	<context:component-scan base-package="com.redis,com.ydtx.moudle,com.ydtx.bean.pojo" />
	<context:component-scan base-package="com.redis"> 
	</context:component-scan>
	<!-- 分解配置 jdbc.properites -->
	<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" />
	 <!-- 配置redis  --> 
    <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/>
    
    <!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
    <context:component-scan
            base-package="com.ydtx.moudle.controller.activiti5">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
	<!-- 数据源c3p0 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="${jdbc.driverClassName}" />
		<property name="jdbcUrl" value="${jdbc.url}" />
		<property name="user" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
		<property name="maxPoolSize" value="${c3p0.pool.size.max}" />
		<property name="minPoolSize" value="${c3p0.pool.size.min}" />
		<property name="initialPoolSize" value="${c3p0.pool.size.ini}" />
		<property name="acquireIncrement" value="${c3p0.pool.size.increment}" />
	</bean>


	<!-- sessionFactory 将spring和mybatis整合 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="configLocation" value="classpath:spring-mybatis.xml" />
		<property name="mapperLocations" value="classpath*:com/ydtx/bean/mapper/**/*.xml" />
	</bean>
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.ydtx.moudle.service" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>
	<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="add*" propagation="REQUIRED" />
			<tx:method name="append*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="modify*" propagation="REQUIRED" />
			<tx:method name="edit*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="remove*" propagation="REQUIRED" />
			<tx:method name="repair" propagation="REQUIRED" />
			<tx:method name="delAndRepair" propagation="REQUIRED" />

			<tx:method name="get*" propagation="SUPPORTS" />
			<tx:method name="find*" propagation="SUPPORTS" />
			<tx:method name="load*" propagation="SUPPORTS" />
			<tx:method name="search*" propagation="SUPPORTS" />
			<tx:method name="datagrid*" propagation="SUPPORTS" />

			<tx:method name="*" propagation="SUPPORTS" />
		</tx:attributes>
	</tx:advice>
	<aop:config>
		<aop:pointcut id="transactionPointcut" expression="execution(* com.ydtx.moudle.service.*.*.*.*(..))" />
		<aop:advisor pointcut-ref="transactionPointcut" advice-ref="transactionAdvice" />
	</aop:config>
	    <!-- 引入同文件夹下的redis属性配置文件 -->
    <import resource="redis-context.xml"/>
</beans>  

3.redis-context.xml

<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" 
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="
            http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
            http://www.springframework.org/schema/tx 
            http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">
    
    
    <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}" />  
        <property name="testOnBorrow" value="${redis.testOnBorrow}" />  
    </bean>  
      
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
        p:host-name="${redis.host}" 
        p:port="${redis.port}" 
        p:password="${redis.pass}"  
        p:pool-config-ref="poolConfig"/>  
      
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory"   ref="connectionFactory" />  
    </bean>      
     
</beans>   
 4.redis.properties
# Redis settings
#redis.host=192.168.20.101
#redis.port=6380
#redis.pass=foobared
redis.host=127.0.0.1
redis.port=6379
redis.pass=
  
redis.maxIdle=300
redis.maxTotal=600
redis.MaxWaitMillis=1000
redis.testOnBorrow=true
 

5.Redis对象持久化操作类

package com.redis;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;

public abstract class RedisGeneratorDao<K extends Serializable, V extends Serializable>  {
    
    @Autowired
    protected RedisTemplate<K,V> redisTemplate ;

    /** 
     * 设置redisTemplate 
     * @param redisTemplate the redisTemplate to set 
     */  
    public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {  
        this.redisTemplate = redisTemplate;  
    }  
      
    /** 
     * 获取 RedisSerializer 
     * <br>------------------------------<br> 
     */  
    protected RedisSerializer<String> getRedisSerializer() {  
        return redisTemplate.getStringSerializer();  
    }  
    
}

 5.在项目中service中使用,直接继承RedisGeneratorDao

IUserInfoService.java

package com.ydtx.moudle.service.system.userInfo;


import com.ydtx.bean.mapper.comm.BaseArgument;
import com.ydtx.bean.pojo.system.User;

public interface IUserInfoService {
	/**
	 * 获取用户信息
	 * @param user
	 * @return
	 */
	public BaseArgument loadInfoData(User user);
	/**
	 * 插入用户信息
	 * @param user
	 * @return
	 */
	public BaseArgument insertUser(User user);
	/**
	 * 删除用户
	 */
	public BaseArgument deleteUser(User user);
	/**
	 * 根据id查询数据
	 * @param staffid
	 * @return
	 */
	public BaseArgument getDataById(int staffid);
	/**
	 * 修改数据
	 * @param user
	 * @return
	 */
	public BaseArgument editData(User user);
	
	/**
	 * Description:更改用户信息 
	 * @author 唐寅建
	 * @date 上午10:22:47
	 */
	public BaseArgument updateUserInfoBySekected (User user);
	public BaseArgument loadAccounts(User user);
}

 UserInfoService.java

package com.ydtx.moudle.service.system.userInfo;


import java.io.Serializable;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import com.redis.RedisGeneratorDao;
import com.ydtx.bean.mapper.comm.BaseArgument;
import com.ydtx.bean.pojo.system.User;
import com.ydtx.moudle.dao.system.userInfo.IUserInfoDao;
@Service("UserInfoService")
public class UserInfoService extends RedisGeneratorDao<Serializable, Serializable> implements IUserInfoService{
	protected static final Logger logger = Logger.getLogger(UserInfoService.class);
	@Autowired
	IUserInfoDao dao;
	@Override
	public BaseArgument loadInfoData(User user) {
			BaseArgument res=new BaseArgument();
			try {
				res=dao.loadInfoData(user);
			} catch (Exception e) {
				logger.error(e.getMessage());
				throw new RuntimeException(e.getMessage());
			}
			// TODO Auto-generated method stub
			return res;
	}
	
	@Override
	public BaseArgument getDataById(int staffid){
		BaseArgument res=new BaseArgument();
		try {
			res=dao.getDataById(staffid);
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
		return res;
	}
	
	@Override
	public BaseArgument editData(User user) {
		BaseArgument res=new BaseArgument();
		try {
			res=dao.editData(user);
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
	    return res;
    }

	@Override
	public BaseArgument insertUser(User user) {
		BaseArgument res=new BaseArgument();
		try {
			res=dao.insertUser(user);
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
	    return res;
    }
	
	@Override
	public BaseArgument deleteUser(User user) {
		BaseArgument res=new BaseArgument();
		try {
			res=dao.deleteUser(user);
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
	    return res;
    }

	@Override
	public BaseArgument updateUserInfoBySekected(final User user) {
		BaseArgument res=new BaseArgument();
		try {
			res=dao.updateUserInfoBySekected(user);
                       //将登陆的用户密码保存在redis中
			redisTemplate.execute(new RedisCallback<Boolean>() {  
	            public Boolean doInRedis(RedisConnection connection)  
	                    throws DataAccessException {  
	                RedisSerializer<String> serializer = getRedisSerializer();  
	                byte[] key  = serializer.serialize(user.getUseraccount());  
	                byte[] name = serializer.serialize(user.getPassword());  
	                connection.set(key, name);  
	                return true;  
	            }  
	        });  
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new RuntimeException(e.getMessage());
		}
	    return res;
	}

	@Override
	public BaseArgument loadAccounts(User user) {
		// TODO Auto-generated method stub
		BaseArgument res=new BaseArgument();
		try {
			res=dao.loadAccounts(user);
		} catch (Exception e) {
			// TODO: handle exception
			logger.error(e.getMessage());
			res.fail();
		}
		return res;
	}
}
6.测试是否将登陆用户成功存入本地redis中

 
7.测试成功

其他文章参考:
    Redis快速入门:http://www.yiibai.com/redis/redis_quick_guide.html    StringRedisTemplate常用语句:http://blog.csdn.net/u011911084/article/details/53435172
 

猜你喜欢

转载自change-java.iteye.com/blog/2383027