周围的人似乎都会redis,我就想看看redis究竟是什么。下面推荐一个学习网站。http://www.runoob.com/ 这个网站有很多基础的课程。在看我的文章之前,你可去这个网站看看redia的基础知识。
本文是把redis最为mysql的缓存来使用的。本文是用的spring-data-redis ,ComboPooledDataSource(数据库连接池),mysql数据库。重点是spring-data-redis 中五种数据基本类型的基本操作,以及redis作为缓存对查询速度的提升。
1.首先是搭建环境
spring-mvc.xml 主要配置了mysql和redis<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.test"/> <context:component-scan base-package="com.test.service" /> <context:component-scan base-package="com.test.cache.redis" /> <!-- class annotation related... end --> <context:annotation-config /> <!-- mybatis related... start --> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <!-- 这里支持多种寻址方式:classpath和file --> <value>classpath:jdbc.properties</value> <value>classpath:redis.properties</value> <!-- 推荐使用file的方式引入,这样可以将配置和代码分离 --> </list> </property> </bean> <!--数据库连接配置--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource " destroy-method="close"> <property name="driverClass" value="${jdbc.driver}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <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> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="configLocation" value="classpath:mybatis-config.xml" /> </bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.test.mapper"/> </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.test.cache.redis.RedisCacheConfig"> <constructor-arg ref="jedisConnectionFactory" /> <constructor-arg ref="redisTemplate" /> <constructor-arg ref="redisCacheManager" /> </bean> <!-- redis config end --></beans> spring-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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 启用spring mvc 注解 --> <context:annotation-config /> <!-- class annotation related... start --> <context:component-scan base-package="com.test.action" /> <!-- class annotation related... end --> <aop:config proxy-target-class="true"> </aop:config> <!-- rest json related... start --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> </bean> <!-- rest json related... end --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- jsp page related... end --></beans> 还有redis的连接配置,redis.properties
# Redis settingsredis.host=127.0.0.1redis.port=6369 redis.pass=redis.dbIndex=0 redis.expiration=3000 redis.maxIdle=300 redis.maxActive=600 redis.maxWait=1000 还有jdbc.properties
jdbc.driver = com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3307/ssms?useUnicode=true&characterEncoding=utf8jdbc.username=rootjdbc.password=root
然后是web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>Archetype Created Web Application</display-name> <!-- character encoding related.....start --><!-- TODO : 将 encodingFilter、sysParamsFilter 两个过滤器交给 spring 管理 --> <filter> <filter-name>encodingFilter</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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 除了加过滤器,由于tomcat默认编码ISO-8859-1,还需要修改 %tomcat%/conf/server.xml Connector 标签加属性 URIEncoding="UTF-8" --> <!-- character encoding related.....end --> <servlet> <servlet-name>mvc-servlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mvc-servlet</servlet-name> <url-pattern> *.do</url-pattern> </servlet-mapping> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> </web-app> 还有最重要的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>com.metaedu</groupId> <artifactId>Spring-Redis</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>Spring-Redis 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> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.2.5.RELEASE</version> <scope>test</scope> </dependency> <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>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</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>
2.生成测试类 redis在本例中只是作为mybatis的缓存,主要还是做查询的优化。 我们要先写一个usermapper.xml
然后,我们还需要写一个RedisService来测试这些查询。
package com.test.service; import org.springframework.data.redis.core.*;import org.springframework.stereotype.Service; import javax.annotation.Resource; @Servicepublic class RedisService { @Resource private RedisTemplate<String,Object> redisTemplate; public ValueOperations<String,Object> valueOperations; public SetOperations<String,Object> setOperations; public ZSetOperations<String,Object> zSetOperations; public HashOperations<String,String,Object> hashOperations; public ListOperations<String,Object> listOperations; public ValueOperations<String,Object> ValueOperationsNewInstance(){ if(valueOperations==null){ valueOperations = redisTemplate.opsForValue(); } return valueOperations; } public ListOperations<String,Object> listOperationsNewInstance(){ if(listOperations==null){ listOperations = redisTemplate.opsForList(); } return listOperations; } public HashOperations <String,String,Object> hashOperationsNewInstance(){ if(hashOperations == null){ hashOperations = redisTemplate.opsForHash(); } return hashOperations; } public SetOperations<String,Object> setOperationsNewInstance(){ if(setOperations == null){ setOperations = redisTemplate.opsForSet(); } return setOperations; } public ZSetOperations<String, Object> ZsetOperationsNewInstance() { if(zSetOperations==null){ zSetOperations = redisTemplate.opsForZSet(); } return zSetOperations; } public void Delete(String key){ redisTemplate.delete(key); } 在redisService中最重要的是RedisTemplate,这个类我们之前在spring-mvc.xml中已经配置过了。这个类会为我们生成redis五种基本数据类型的操作类。 我们可以自己生成一个测试类来实际操作下这五种基本类型。以下是我的测试类:
这里要使用springJunitTest,不要单独使用junit,因为我们的RedisTemplate是配置在文档里面的。
我们来看下这五种基本数据类型的操作:
1.String(redis) ----》ValueOperations(spriing-data-redis)
ValueOperations valueOperations = redisTemplate.opsForValue();
以下是测试类(我们根据时间差来查看redis的缓存效果):
下面是用ValueOperations保存数据并取出数据的操作:
下面是运行结果:
2.Hash(redis) --->HashOperations(spring-data-redis)
HashOperations hashOperations = redisTemplate.opsForHash();
下面是测试类(我们根据时间差来查看redis的缓存效果):
下面是用HashOperations保存并取出数据的操作:
以下是运行结果;
3.list(redis) --->ListOperations(spring-data-redis)
ListOperations listOperations = redisTemplate.opsForList();
留给读者自己去实践。。。。
4.set(redis) --->SetOperations(spring-data-redis)
SetOperations setOperations = redisTemplate.opsForSet();
留给读者自己去实践。。。。。
5.zset(redis) --->ZSetOperations(spring-data-redis)
ZSetOperations zSetOperations = redisTemplate.opsForZSet();
zSetOperation 实际上就是一个有序的set 。
下面是测试类(我们根据时间差来查看redis的缓存效果):
下面是用ZSetOperations 来保存数据并取出的操作:
public User findUserById(String id){ //查看缓存有没有数据 if (redisService.ZsetOperationsNewInstance().range(id,0,-1).size()==0){ //缓存中没有就从数据库中取出 User user = usermapper.findUserById(id); //并保存到redis缓存中(ZSet保存) redisService.ZsetOperationsNewInstance().add(id,user,Double.valueOf(id)); System.out.println("数据库查询 用户名" +user.getUsername()); return user; }else{ //如果缓存中有,就从缓存中取出 Set<Object> users= redisService.ZsetOperationsNewInstance().range(id,0,-1); Iterator<Object> it = users.iterator(); while(it.hasNext()){ Object object= it.next(); User user = (User) object; System.out.println("Redis查询 用户名" +user.getUsername()); return user; } return null; }}
我们来看下运行结果:
3.结论
从上面的运行结果中,我们可以看到redis大大提高了我们的查询速度。另外在测试的时候。redis不允许有重复的key,所以要记得删除。
关于redis更高深的东西,后续研究后再更新。