redis是一种非关系型数据库,与mongoDB不同的是redis是内存数据库,所以访问速度很快。常用作缓存和发布-订阅式的消息队列。redis官方没有提供windows版本的软件。windows版本一直是微软维护的。
下载地址:https://github.com/MSOpenTech/redis/releases。
这里是redis相关的教程。http://muxiulin.cn/archives/1197
在spring中集成redis很简单,这里用的是ssm框架+maven构建的项目。
首先是需要引入的pom.xml文件:
<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>
项目基本架构:
jdbc.properties:
jdbc.host=127.0.0.1 jdbc.database=user jdbc.port=3306 jdbc.username=root jdbc.password=root
log4j.properties:
# 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:
<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(); } }; } }
发表评论 取消回复