redis是一種非關係型數據庫,與mongoDB不一樣的是redis是內存數據庫,因此訪問速度很快。經常使用做緩存和發佈-訂閱式的消息隊列。redis官方沒有提供windows版本的軟件。windows版本一直是微軟維護的。java
下載地址:https://github.com/MSOpenTech/redis/releases。mysql
這裏是redis相關的教程。http://muxiulin.cn/archives/1197git
在spring中集成redis很簡單,這裏用的是ssm框架+maven構建的項目。github
首先是須要引入的pom.xml文件:web
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>SSMRedisDemo</groupId> <artifactId>SSMRedisDemo</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>SSMRedisDemo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.2.0.RELEASE</spring.version> </properties> <dependencies> <!-- spring mvc related.....start --> <!-- TODO: replace jackson with fastjson --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.3</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.1</version> </dependency> <!-- spring mvc related.....end --> <!-- mybatis orm related.....start --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.12</version> </dependency> <!-- mybatis orm related.....end --> <!-- project log related.....start --> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!-- project log related.....end --> <!-- redis cache related.....start --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.0.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency> <!-- redis cache related.....end --> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <warSourceDirectory>WebContent</warSourceDirectory> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project>
項目基本架構:redis
jdbc.properties:spring
jdbc.host=127.0.0.1 jdbc.database=user jdbc.port=3306 jdbc.username=root jdbc.password=root
log4j.properties:sql
# Global logging configuration log4j.rootLogger=WARN,stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c:%L - %m%n # mybatis log log4j.logger.com.ssm.dao.UserMapper=DEBUG # lyz log log4j.logger.com.ssm.controller=DEBUG log4j.logger.com.ssm.service=DEBUG
redis.porperties:數據庫
# Redis settings redis.host=127.0.0.1 redis.port=6379 #redis.pass=password redis.dbIndex=0 redis.expiration=3000 redis.maxIdle=300 redis.maxActive=600 redis.maxWait=1000 redis.testOnBorrow=true
applicationContext.xml:apache
<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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <!-- class annotation related... start --> <context:component-scan base-package="com.ssm.serviceImpl" /> <context:component-scan base-package="com.ssm.utils" /> <!-- class annotation related... end --> <!-- mybatis related... start --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:jdbc.properties</value> <value>classpath:redis.properties</value> </list> </property> </bean> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource " destroy-method="close"> <property name="driverClass" value="com.mysql.jdbc.Driver" /> <property name="jdbcUrl" value="jdbc:mysql://${jdbc.host}:${jdbc.port}/${jdbc.database}?useUnicode=true&characterEncoding=utf8" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> <property name="acquireIncrement" value="1" /> <property name="initialPoolSize" value="5" /> <property name="maxPoolSize" value="20" /> <property name="minPoolSize" value="5" /> <property name="maxStatements" value="100" /> <property name="testConnectionOnCheckout" value="true" /> </bean> <!-- spring和MyBatis完美整合,不須要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 自動掃描mapping.xml文件 <property name="mapperLocations" value="classpath:com/ssm/mapper/*.xml"></property> --> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ssm.dao" /> </bean> <!-- mybatis related... end --> <!-- transaction config related... start --> <tx:annotation-driven transaction-manager="transactionManager" /> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- transaction config related... end --> <!-- redis config start --> <!-- 配置JedisPoolConfig實例 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}" /> <property name="maxTotal" value="${redis.maxActive}" /> <property name="maxWaitMillis" value="${redis.maxWait}" /> <property name="testOnBorrow" value="${redis.testOnBorrow}" /> </bean> <!-- 配置JedisConnectionFactory --> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}" /> <property name="port" value="${redis.port}" /> <!-- <property name="password" value="${redis.pass}" /> --> <property name="database" value="${redis.dbIndex}" /> <property name="poolConfig" ref="poolConfig" /> </bean> <!-- 配置RedisTemplate --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory" /> </bean> <!-- 配置RedisCacheManager --> <bean id="redisCacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg name="redisOperations" ref="redisTemplate" /> <property name="defaultExpiration" value="${redis.expiration}" /> </bean> <!-- 配置RedisCacheConfig --> <bean id="redisCacheConfig" class="com.ssm.utils.RedisCacheConfig"> <constructor-arg ref="jedisConnectionFactory" /> <constructor-arg ref="redisTemplate" /> <constructor-arg ref="redisCacheManager" /> </bean> <!-- redis config end --> </beans>
springmvc.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" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- class annotation related... start <context:component-scan base-package="com.ssm.controller" /> class annotation related... end --> <!-- 添加註解驅動 使用註解標註的類生效--> <mvc:annotation-driven /> <!-- 設置能訪問靜態資源 --> <mvc:default-servlet-handler/> <!--掃描controller--> <context:component-scan base-package="com.ssm.controller" /> <!-- jsp page related... start --> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- jsp page related... end --> <!-- rest json related... start --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>application/json;charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> </list> </property> </bean> <!-- rest json related... end --> </beans>
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list> <!-- 加載spring bean --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 編碼過濾器 --> <filter> <filter-name>springfilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>springfilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- Spring MVC servlet --> <servlet> <servlet-name>SpringMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>SpringMVC</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
UserController:
package com.ssm.controller; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.ssm.pojo.User; import com.ssm.service.IUserService; /** * user控制器 * * @author YaoQi */ @Controller @RequestMapping("/UserCRUD") public class UserController { @Resource private IUserService userService; /** * 查詢全部User * * @param request * @param model * @return */ @RequestMapping(value = "/showUser", method = RequestMethod.GET) public String showUsers(Model model) { System.out.println("**********showUsers********"); List<User> userList = new ArrayList<User>(); userList = userService.getAllUser(); model.addAttribute("userList", userList); // 填充數據到model return "showUser"; } /** * 增長一個用戶 * * @param userName * @param sex * @param age * @return */ @RequestMapping(value = "/addUser", method = RequestMethod.POST) @ResponseBody public ModelMap addUser(String userName, String sex, int age) { System.out.println("******addUser********"); System.out.println(userName + sex + age); User user = new User(); user.setsex(sex); user.setUserName(userName); user.setAge(age); userService.insertUser(user); ModelMap model = new ModelMap(); model.addAttribute("result", "添加成功"); return model; } /** * 經過userID刪除用戶 * * @param userID */ @RequestMapping(value = "/delUser/{userID}", method = RequestMethod.GET) public ModelAndView delUser(@PathVariable int userID) { System.out.println(userID); userService.deleteUser(userID); ModelAndView mv = new ModelAndView(); List<User> userList = new ArrayList<User>(); userList = userService.getAllUser(); mv.addObject("userList", userList); // 填充數據到model mv.setViewName("showUser"); return mv; } /** * 查詢用戶 * * @param model * @param keyWords * @return */ @RequestMapping(value = "/search", method = RequestMethod.POST) public String findUsers(Model model, String keyWords) { System.out.println(keyWords); List<User> userList = new ArrayList<User>(); userList = userService.findUsers(keyWords); model.addAttribute("userList", userList); // 填充數據到model return "showUser"; } /** * 更新用戶信息 * @param userName * @param sex * @param age * @param id * @return */ @RequestMapping(value="/editUser",method=RequestMethod.POST) public ModelAndView editUser(String userName, String sex, int age, int id) { System.out.println(userName + sex + age); User user = new User(); user.setsex(sex); user.setUserName(userName); user.setAge(age); user.setId(id); userService.editUser(user); ModelAndView mv = new ModelAndView(); List<User> userList = new ArrayList<User>(); userList = userService.getAllUser(); mv.addObject("userList", userList); // 填充數據到model mv.setViewName("redirect:/UserCRUD/showUser"); return mv; } }
User:
package com.ssm.pojo; import java.io.Serializable; /** * User實體類對應數據庫中的tb_user表 * * @author YaoQi * 要想使用redis存對象,必定要讓實體類實現Serializable接口,不然會報錯。 */ public class User implements Serializable{ /** * */ private static final long serialVersionUID = -5244288298702801619L; private int id; private String userName; private String sex; private int age; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getsex() { return sex; } public void setsex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "User [id=" + id + ", userName=" + userName + ", sex=" + sex + ", age=" + age + "]"; } }
UserMapper:
package com.ssm.dao; import java.util.List; import com.ssm.pojo.User; public interface UserMapper { public User selectByPrimaryKey(int userId); public List<User> selectAllUser(); public void insertUser(User user); public void deleteUser(int id); public List<User> findUsers(String keyWords); public void editUser(User user); }
UserMapper.xml: 與對應的接口放到同一包下面。
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.ssm.dao.UserMapper"> <resultMap id="BaseResultMap" type="com.ssm.pojo.User"> <id column="id" property="id" jdbcType="INTEGER" /> <result column="userName" property="userName" jdbcType="VARCHAR" /> <result column="sex" property="sex" jdbcType="VARCHAR" /> <result column="age" property="age" jdbcType="INTEGER" /> </resultMap> <sql id="Base_Column_List"> id,userName,sex,age </sql> <select id="findUsers" resultMap="BaseResultMap" parameterType="String"> select <include refid="Base_Column_List" /> from tb_user where id like #{keyWords} or userName like #{keyWords} or sex like #{keyWords} or age like #{keyWords} </select> <!-- 查詢全部的user --> <select id="selectAllUser" resultMap="BaseResultMap"> select <include refid="Base_Column_List" /> from tb_user </select> <!-- 添加一個用戶 --> <insert id="insertUser" parameterType="com.ssm.pojo.User"> INSERT INTO tb_user(userName,sex,age) VALUES (#{userName},#{sex},#{age}) </insert> <!-- 刪除用戶 --> <delete id="deleteUser" parameterType="int"> DELETE FROM tb_user WHERE id=#{id} </delete> <!-- 更新user信息 --> <update id="editUser" parameterType="com.ssm.pojo.User"> UPDATE tb_user SET userName=#{userName}, sex=#{sex},age=#{age} WHERE id=#{id} </update> </mapper>
IUserService:
package com.ssm.service; import java.util.List; import com.ssm.pojo.User; /** * user表的操做接口 * @author YaoQi */ public interface IUserService { /** * 經過id查詢user接口方法 * @param userId * @return */ public User getUserById(int userId); /** * 查詢全部的user * @return 返回userList */ public List<User> getAllUser(); /** * 添加一個user * @param user */ public void insertUser(User user); /** * 經過ID刪除用戶 * @param id */ public void deleteUser(int id); /** * 經過關鍵字查詢用戶 * @param keyWords * @return */ public List<User> findUsers(String keyWords); /** * 更新用戶 * @param user */ public void editUser(User user); }
ServiceImple:
package com.ssm.serviceImpl; import java.util.List; import javax.annotation.Resource; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.ssm.dao.UserMapper; import com.ssm.pojo.User; import com.ssm.service.IUserService; /** * userService * * 緩存機制說明:全部的查詢結果都放進了緩存,也就是把MySQL查詢的結果放到了redis中去, * 而後第二次發起該條查詢時就能夠從redis中去讀取查詢的結果,從而不與MySQL交互,從而達到優化的效果, * redis的查詢速度之於MySQL的查詢速度至關於 內存讀寫速度 /硬盤讀寫速度 * @Cacheable("a")註解的意義就是把該方法的查詢結果放到redis中去,下一次再發起查詢就去redis中去取,存在redis中的數據的key就是a; * @CacheEvict(value={"a","b"},allEntries=true) 的意思就是執行該方法後要清除redis中key名稱爲a,b的數據; */ @Service("userService") @Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) public class UserServiceImpl implements IUserService { @Resource private UserMapper iUserDao; @Cacheable("getUserById") //標註該方法查詢的結果進入緩存,再次訪問時直接讀取緩存中的數據 @Override public User getUserById(int userId) { return this.iUserDao.selectByPrimaryKey(userId); } @Cacheable("getAllUser") @Override public List<User> getAllUser() { return this.iUserDao.selectAllUser(); } @CacheEvict(value= {"getAllUser","getUserById","findUsers"},allEntries=true)//清空緩存,allEntries變量表示全部對象的緩存都清除 @Override public void insertUser(User user) { this.iUserDao.insertUser(user); } @CacheEvict(value= {"getAllUser","getUserById","findUsers"},allEntries=true) @Override public void deleteUser(int id) { this.iUserDao.deleteUser(id); } @Cacheable("findUsers") @Override public List<User> findUsers(String keyWords) { return iUserDao.findUsers(keyWords); } @CacheEvict(value= {"getAllUser","getUserById","findUsers"},allEntries=true) @Override public void editUser(User user) { this.iUserDao.editUser(user); } }
緩存主要在service層進行,查詢的結果會緩存,把對象序列號存到redis中去,key就是註解中的參數,例如@Cacheable("findUsers"): 存在redis中的key就是findUsers。緩存了這個結果以後再次請求這個方法就不會去數據庫中查,而是從redis緩存中讀取數據,這樣就減小了跟數據庫之間的交互。而後修改、刪除、增長操做就會清除緩存,保持數據的一致性。
RedisCacheConfig: 須要增長這個配置類,會在applicationContex配置文件中註冊這個bean。
package com.ssm.utils; import java.lang.reflect.Method; import org.springframework.cache.annotation.CachingConfigurerSupport; import org.springframework.cache.annotation.EnableCaching; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheManager; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; /** * 經過spring管理redis緩存配置 * * @author Administrator * */ @Configuration @EnableCaching public class RedisCacheConfig extends CachingConfigurerSupport { private volatile JedisConnectionFactory jedisConnectionFactory; private volatile RedisTemplate<String, String> redisTemplate; private volatile RedisCacheManager redisCacheManager; public RedisCacheConfig() { super(); } /** * 帶參數的構造方法 初始化全部的成員變量 * * @param jedisConnectionFactory * @param redisTemplate * @param redisCacheManager */ public RedisCacheConfig(JedisConnectionFactory jedisConnectionFactory, RedisTemplate<String, String> redisTemplate, RedisCacheManager redisCacheManager) { this.jedisConnectionFactory = jedisConnectionFactory; this.redisTemplate = redisTemplate; this.redisCacheManager = redisCacheManager; } public JedisConnectionFactory getJedisConnecionFactory() { return jedisConnectionFactory; } public RedisTemplate<String, String> getRedisTemplate() { return redisTemplate; } public RedisCacheManager getRedisCacheManager() { return redisCacheManager; } @Bean public KeyGenerator customKeyGenerator() { return new KeyGenerator() { @Override public Object generate(Object target, Method method, Object... objects) { StringBuilder sb = new StringBuilder(); sb.append(target.getClass().getName()); sb.append(method.getName()); for (Object obj : objects) { sb.append(obj.toString()); } return sb.toString(); } }; } }