Springmvc integrated redis architecture to build an example
for a long time, because my company is mainly engaged in ERP system, I am mainly responsible for the development of these products, recently interviewed some developers to use redis cache for web development, because I have never used it, I don’t know much about it, so I solved it by the way. By the way, I tested and integrated redis in the company’s existing projects. The specific configuration code is posted below:
1. Configuration file
2. Use redis 64-bit download address:
http://download.csdn.net/download/xmt1139057136/9220075
Step 1: Create a maven project:
1. Introduce the jedis and spring-data-redis rack packages into the existing pom.xml:
<!-- redis integration--> <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 integration-->
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"> <!-- Scan service, dao components--> <context:component-scan base-package="com.redis,com.ydtx.moudle,com.ydtx.bean.pojo" /> <context:component-scan base-package="com.redis"> </context:component-scan> <!-- Decomposition configuration jdbc.properites --> <context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true" /> <!-- configure redis --> <context:property-placeholder location="classpath:redis.properties" ignore-unresolvable="true"/> <!-- Use annotation to automatically register beans, and ensure that @Required, @Autowired properties are injected --> <context:component-scan base-package="com.ydtx.moudle.controller.activiti5"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- data source 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 integrates spring and 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> <!-- Introduce the redis attribute configuration file in the same folder --> <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 object persistence operation class
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 ; /** * Set redisTemplate * @param redisTemplate the redisTemplate to set */ public void setRedisTemplate (RedisTemplate <K, V> redisTemplate) { this.redisTemplate = redisTemplate; } /** * Get RedisSerializer * <br>------------------------------<br> */ protected RedisSerializer<String> getRedisSerializer() { return redisTemplate.getStringSerializer(); } }
5. Use in the service in the project, directly inherit 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 { /** * Get user information * @param user * @return */ public BaseArgument loadInfoData(User user); /** * Insert user information * @param user * @return */ public BaseArgument insertUser(User user); /** * delete users */ public BaseArgument deleteUser(User user); /** * Query data by id * @param staffid * @return */ public BaseArgument getDataById(int staffid); /** * change the data * @param user * @return */ public BaseArgument editData(User user); /** * Description: Change user information * @author Tang Yinjian * @date 10:22:47 AM */ 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); //Save the logged in user password in 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. Test whether the login user is successfully stored in the local redis
7. The test is successful Other article references: Redis Quick Start: http://www.yiibai.com/redis/redis_quick_guide.html StringRedisTemplate Common Statements: http://blog.csdn.net/u011911084/article/details/53435172