1.1 首先创建一个Maven工程
File --> New --> Other,然后选择Maven目录下的Maven Project,如下图:
然后在弹出的面板中选择配置后,下一步即可,如图:
Create a simple project (skip archetype selection) :此选项表示跳过后续的配置选项框。
Use default Workspace location:表示将项目放置到默认的工作区域下。
配置好后,Next下一步,再进行如下图的配置:
点击Finish后,便完成了Maven工程的创建。
此时在你开发工具的Workspace工作区的树桩菜单中出现了SpringRedisStudy这个项目工程.如图:
这时,工程会报错,是因为一开始创建Maven工程时,选择的是 Create a simple project 属性,所以在webapp项目下可能会没有任何文件,如图:
这个时候就需要我们自己去创建它们。
首先在 webapp 下增加一个 WEB-INF 文件夹;然后在 WEB-INF 文件夹中增加一个 web.xml(部署描述符文件);
接下来我们就要在这个文件中进行一些配置工作。
1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" 3 xmlns="http://java.sun.com/xml/ns/javaee" 4 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 5 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 6 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 7 <display-name>SpringRedisStudy</display-name> 8 <!-- 设置由Sprng载入的Log4j配置文件位置 --> 9 <context-param> 10 <param-name>log4jConfigLocation</param-name> 11 <param-value>classpath:config/property/log4j.properties</param-value> 12 </context-param> 13 <!-- Spring刷新Log4j配置文件变动的间隔,单位为毫秒 --> 14 <context-param> 15 <param-name>log4jRefreshInterval</param-name> 16 <param-value>100000</param-value> 17 </context-param> 18 <!-- 加载其他配置文件至Spring应用上下文中 --> 19 <listener> 20 <listener-class> 21 org.springframework.web.context.ContextLoaderListener 22 </listener-class> 23 </listener> 24 <!-- 指定多个Spring配置文件 --> 25 <context-param> 26 <param-name>contextConfigLocation</param-name> 27 <param-value> 28 classpath:config/xml/dispatcher-servlet.xml; 29 classpath:config/xml/spring-context.xml 30 </param-value> 31 </context-param> 32 <!-- Spring字符集过滤器 --> 33 <filter> 34 <filter-name>SpringEncodingFilter</filter-name> 35 <filter-class>org.springframework.web.filter.CharacterEncodingFilter 36 </filter-class> 37 <init-param> 38 <param-name>encoding</param-name> 39 <param-value>UTF-8</param-value> 40 </init-param> 41 <init-param> 42 <param-name>forceEncoding</param-name> 43 <param-value>true</param-value> 44 </init-param> 45 </filter> 46 <filter-mapping> 47 <filter-name>SpringEncodingFilter</filter-name> 48 <url-pattern>/*</url-pattern> 49 </filter-mapping> 50 51 <!-- Spring view分发器 --> 52 <!-- servlet-name 决定了初始化的名字:name-servlet.xml --> 53 <servlet> 54 <servlet-name>dispatcher</servlet-name> 55 <servlet-class>org.springframework.web.servlet.DispatcherServlet 56 </servlet-class> 57 <init-param> 58 <param-name>contextConfigLocation</param-name> 59 <param-value>/WEB-INF/classes/conf/dispatcher-servlet.xml 60 </param-value> 61 </init-param> 62 <load-on-startup>2</load-on-startup> 63 </servlet> 64 <servlet-mapping> 65 <servlet-name>dispatcher</servlet-name> 66 <url-pattern>/</url-pattern> 67 </servlet-mapping> 68 69 <welcome-file-list> 70 <welcome-file>index.jsp</welcome-file> 71 </welcome-file-list> 72 73 </web-app>
1.2 配置maven 工程文件 pom.xml
接下来我们进行详细的项目搭建,首先配置maven 工程文件 pom.xml,
因为我们要搭建Spring MVC这个工程,所以就要将相关的jar包配置到Maven工程中进行引用管理;
pom.xml文件配置如下:
1 <project xmlns="http://maven.apache.org/POM/4.0.0" 2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 4 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 <groupId>SpringRedisStudy</groupId> 7 <artifactId>SpringRedisStudy</artifactId> 8 <version>0.0.1-SNAPSHOT</version> 9 <packaging>war</packaging> 10 <properties> 11 <!-- spring版本号 --> 12 <org.springframework.version>3.0.7.RELEASE</org.springframework.version> 13 <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> 14 <slf4j.version>1.7.5</slf4j.version> 15 <log4j.version>1.2.17</log4j.version> 16 </properties> 17 18 <dependencies> 19 20 <!-- config junit jar --> 21 <dependency> 22 <groupId>junit</groupId> 23 <artifactId>junit</artifactId> 24 <version>4.8.2</version> 25 <scope>test</scope> 26 </dependency> 27 28 <!-- config redis data and client jar --> 29 <dependency> 30 <groupId>org.springframework.data</groupId> 31 <artifactId>spring-data-redis</artifactId> 32 <version>1.6.4.RELEASE</version> 33 </dependency> 34 <dependency> 35 <groupId>redis.clients</groupId> 36 <artifactId>jedis</artifactId> 37 <version>2.7.3</version> 38 </dependency> 39 <dependency> 40 <groupId>org.apache.commons</groupId> 41 <artifactId>commons-pool2</artifactId> 42 <version>2.4.2</version> 43 </dependency> 44 45 <!-- config need jar --> 46 <dependency> 47 <groupId>commons-lang</groupId> 48 <artifactId>commons-lang</artifactId> 49 <version>2.6</version> 50 </dependency> 51 52 <dependency> 53 <groupId>org.apache.geronimo.specs</groupId> 54 <artifactId>geronimo-servlet_3.0_spec</artifactId> 55 <version>1.0</version> 56 </dependency> 57 58 <!-- cofig spring jar --> 59 <dependency> 60 <groupId>org.springframework</groupId> 61 <artifactId>spring-core</artifactId> 62 <version>${org.springframework.version}</version> 63 </dependency> 64 65 <dependency> 66 <groupId>org.springframework</groupId> 67 <artifactId>spring-expression</artifactId> 68 <version>${org.springframework.version}</version> 69 </dependency> 70 71 <dependency> 72 <groupId>org.springframework</groupId> 73 <artifactId>spring-beans</artifactId> 74 <version>${org.springframework.version}</version> 75 </dependency> 76 77 <dependency> 78 <groupId>org.springframework</groupId> 79 <artifactId>spring-aop</artifactId> 80 <version>${org.springframework.version}</version> 81 </dependency> 82 83 <dependency> 84 <groupId>org.springframework</groupId> 85 <artifactId>spring-context</artifactId> 86 <version>${org.springframework.version}</version> 87 </dependency> 88 89 <dependency> 90 <groupId>org.springframework</groupId> 91 <artifactId>spring-context-support</artifactId> 92 <version>${org.springframework.version}</version> 93 </dependency> 94 95 <dependency> 96 <groupId>org.springframework</groupId> 97 <artifactId>spring-tx</artifactId> 98 <version>${org.springframework.version}</version> 99 </dependency> 100 101 <dependency> 102 <groupId>org.springframework</groupId> 103 <artifactId>spring-jdbc</artifactId> 104 <version>${org.springframework.version}</version> 105 </dependency> 106 107 <dependency> 108 <groupId>org.springframework</groupId> 109 <artifactId>spring-orm</artifactId> 110 <version>${org.springframework.version}</version> 111 </dependency> 112 113 <dependency> 114 <groupId>org.springframework</groupId> 115 <artifactId>spring-oxm</artifactId> 116 <version>${org.springframework.version}</version> 117 </dependency> 118 119 <dependency> 120 <groupId>org.springframework</groupId> 121 <artifactId>spring-web</artifactId> 122 <version>${org.springframework.version}</version> 123 </dependency> 124 125 <dependency> 126 <groupId>org.springframework</groupId> 127 <artifactId>spring-webmvc</artifactId> 128 <version>${org.springframework.version}</version> 129 </dependency> 130 131 132 <dependency> 133 <groupId>org.springframework</groupId> 134 <artifactId>spring-webmvc-portlet</artifactId> 135 <version>${org.springframework.version}</version> 136 </dependency> 137 138 <dependency> 139 <groupId>org.springframework</groupId> 140 <artifactId>spring-test</artifactId> 141 <version>${org.springframework.version}</version> 142 <scope>test</scope> 143 </dependency> 144 <!-- log start --> 145 <dependency> 146 <groupId>log4j</groupId> 147 <artifactId>log4j</artifactId> 148 <version>${log4j.version}</version> 149 </dependency> 150 <dependency> 151 <groupId>commons-logging</groupId> 152 <artifactId>commons-logging</artifactId> 153 <version>1.2</version> 154 </dependency> 155 <dependency> 156 <groupId>org.slf4j</groupId> 157 <artifactId>slf4j-api</artifactId> 158 <version>${slf4j.version}</version> 159 </dependency> 160 <dependency> 161 <groupId>org.slf4j</groupId> 162 <artifactId>slf4j-log4j12</artifactId> 163 <version>${slf4j.version}</version> 164 </dependency> 165 <!-- log end --> 166 </dependencies> 167 168 <build> 169 <resources> 170 <resource> 171 <directory>/src/main/resources</directory> 172 <filtering>true</filtering> 173 </resource> 174 </resources> 175 <plugins> 176 <plugin> 177 <artifactId>maven-war-plugin</artifactId> 178 <configuration> 179 <version>2.5</version> 180 </configuration> 181 </plugin> 182 </plugins> 183 </build> 184 </project>
1.3 集成spring配置文件
Maven配置好后,我们就需要在项目中进行spring配置了;
在src/main/resources目录中增加一个 config.xml包,并新建文件spring-context.xml;
这个文件的作用是配置Spring的,内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:mvc="http://www.springframework.org/schema/mvc" 6 xmlns:context="http://www.springframework.org/schema/context" 7 xmlns:util="http://www.springframework.org/schema/util" 8 xsi:schemaLocation="http://www.springframework.org/schema/beans 9 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 10 http://www.springframework.org/schema/context 11 http://www.springframework.org/schema/context/spring-context-3.0.xsd 12 http://www.springframework.org/schema/mvc 13 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 14 http://www.springframework.org/schema/util 15 http://www.springframework.org/schema/util/spring-util-3.0.xsd"> 16 17 <!-- 激活@Controller模式 --> 18 <mvc:annotation-driven /> 19 <context:annotation-config /> 20 <!-- 对包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 需要更改 --> 21 <context:component-scan base-package="com.test.*" /> 22 23 <!-- 引入同文件夹下的redis属性配置文件 --> 24 <import resource="redis-context.xml"/> 25 <!-- 测试用的userDao依赖注入 --> 26 <bean id="userDao" class="com.test.dao.impl.UserDao" /> 27 </beans>
在该包config.xml下同时新建redis-context.xml文件,内容如下:
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xmlns:p="http://www.springframework.org/schema/p" 5 xmlns:context="http://www.springframework.org/schema/context" 6 xsi:schemaLocation=" 7 http://www.springframework.org/schema/beans 8 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 9 http://www.springframework.org/schema/context 10 http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 11 12 <!-- 引入redis.properties配置文件 --> 13 <context:property-placeholder 14 location="classpath:/config/property/redis.properties" /> 15 <!-- redis 相关配置 --> 16 <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig" 17 p:maxTotal="${redis.maxTotal}" 18 p:maxIdle="${redis.maxIdle}" 19 p:testOnBorrow="${redis.testOnBorrow}" /> 20 21 <bean id="connectionFactory" 22 class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" 23 p:hostName="${redis.host}" 24 p:port="${redis.port}" 25 p:password="${redis.password}" 26 p:database="${redis.database}" 27 p:pool-config-ref="poolConfig" /> 28 <!-- redis template definition --> 29 <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" 30 p:connectionFactory-ref="connectionFactory" 31 p:keySerializer-ref="redisTemplateKeySerializer" 32 p:valueSerializer-ref="redisTemplateValueSerializer" 33 p:hashKeySerializer-ref="redisTemplateHashKeySerializer" 34 p:hashValueSerializer-ref="redisTemplateHashValueSerializer"/> 35 <bean id="redisTemplateKeySerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 36 <bean id="redisTemplateValueSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 37 <bean id="redisTemplateHashKeySerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer" /> 38 <bean id="redisTemplateHashValueSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> 39 </beans>
在src/main/resources目录中增加一个config.property包,并新建文件redis.properties,这个文件是redis的属性配置文件,内容如下:
# Redis settings # server IP redis.host=127.0.0.1 # server port redis.port=6379 redis.password=myredis redis.maxTotal=600 #redis.maxActive=600 此属性在新版本中不可用 # use dbIndex redis.database=0 # 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例 redis.maxIdle=300 # 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间(毫秒),则直接抛出JedisConnectionException; #redis.maxWait=3000 此属性在新版本中不可用 # 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的 redis.testOnBorrow=true
在src/main/resources目录下新建log4j.properties文件,作为log4j的属性配置文件,内容如下:
#All level less than INFO will be logged log4j.rootLogger=info,console log4j.appender.console=org.apache.log4j.ConsoleAppender log4j.appender.console.ImmediateFlush=true log4j.appender.console.Target=System.out log4j.appender.console.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %m%n
在项目工程未上线前暂时放在该目录,方便测试,上线后可以移动到config.property目录,此时需要在web.xml文件的<listener>节点前加入如下内容:
1 …… 2 <display-name>SpringRedisStudy</display-name> 3 <!-- 设置由Sprng载入的Log4j配置文件位置 --> 4 <context-param> 5 <param-name>log4jConfigLocation</param-name> 6 <param-value>classpath:config/property/log4j.properties</param-value> 7 </context-param> 8 <!-- Spring刷新Log4j配置文件变动的间隔,单位为毫秒 --> 9 <context-param> 10 <param-name>log4jRefreshInterval</param-name> 11 <param-value>100000</param-value> 12 </context-param> 13 <!-- 加载其他配置文件至Spring应用上下文中 --> 14 <listener> 15 ……
1.4 编写java类
在SpringRedisStudy工程的src/main/java目录下新建com.test.entity包,并新建User.java类,内容如下:
package com.test.entity; import java.io.Serializable; public class User implements Serializable{ private static final long serialVersionUID = 8634600086311962551L; private String id; private String name; public User() { super(); } public User(String id, String name) { super(); this.id = id; this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
在SpringRedisStudy工程的src/main/java目录下新建com.test.dao包并在该包下新建抽象类AbstractBaseRedisDao.java和接口IUserDao.java文件,内容如下:
package com.test.dao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; public abstract class AbstractBaseRedisDao <K, V> { @Autowired protected RedisTemplate<K, V> redisTemplate; /** * 设置redisTemplate * @param redisTemplate 给属性redisTemplate赋值 */ public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) { this.redisTemplate = redisTemplate; } /** * 获取 RedisSerializer */ protected RedisSerializer<String> getRedisSerializer() { return redisTemplate.getStringSerializer(); } }
package com.test.dao; import java.util.List; import com.test.entity.User; public interface IUserDao { /** * 新增 * @param User对象 * @return 是否新增成功 */ boolean add(User user); /** * 批量新增 使用pipeline方式 * @param list * @return 是否新增成功 */ boolean add(List<User> list); /** * 删除 * @param key */ void delete(String key); /** * 删除多个 * @param keys */ void delete(List<String> keys); /** * 修改 * @param user对象 * @return 是否修改成功 */ boolean update(User user); /** * 通过key获取User对象 * @param keyId * @return User对象 */ User get(String keyId); }
在SpringRedisStudy工程的src/main/java目录下新建com.test.dao.impl包并在该包下新建接口的实现类UserDao.java文件,内容如下:
package com.test.dao.impl; import java.util.ArrayList; import java.util.List; 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.util.Assert; import com.test.dao.AbstractBaseRedisDao; import com.test.dao.IUserDao; import com.test.entity.User; public class UserDao extends AbstractBaseRedisDao <String, User> implements IUserDao { /** * 新增 * @param User对象 * @return 是否新增成功 */ public boolean add(final User user) { boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(user.getId()); byte[] name = serializer.serialize(user.getName()); return connection.setNX(key, name); } }); return result; } /** * 批量新增 使用pipeline方式 * @param list * @return 是否新增成功 */ public boolean add(final List<User> list) { Assert.notEmpty(list); boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); for (User user : list) { byte[] key = serializer.serialize(user.getId()); byte[] name = serializer.serialize(user.getName()); connection.setNX(key, name); } return true; } }, false, true); return result; } /** * 删除 * @param key */ public void delete(String key) { if (key ==null || key.length() == 0) { return; } List<String> list = new ArrayList<String>(); list.add(key); delete(list); } /** * 删除多个 * @param keys */ public void delete(List<String> keys) { redisTemplate.delete(keys); } /** * 修改 * @param user * @return result 是否修改成功 */ public boolean update(final User user) { String key = user.getId(); if (get(key) == null) { throw new NullPointerException("数据行不存在, key = " + key); } boolean result = redisTemplate.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(user.getId()); byte[] name = serializer.serialize(user.getName()); connection.set(key, name); return true; } }); return result; } /** * 通过key获取User对象 * @param keyId * @return User对象 */ public User get(final String keyId) { User result = redisTemplate.execute(new RedisCallback<User>() { public User doInRedis(RedisConnection connection) throws DataAccessException { RedisSerializer<String> serializer = getRedisSerializer(); byte[] key = serializer.serialize(keyId); byte[] value = connection.get(key); if (value == null) { return null; } String name = serializer.deserialize(value); return new User(keyId, name); } }); return result; } }
在SpringRedisStudy工程的src/test/java目录的默认default包下新建测试类RedisTest.java文件,内容如下:
import java.util.ArrayList; import java.util.List; import junit.framework.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import com.test.dao.IUserDao; import com.test.entity.User; /** * 测试 */ @ContextConfiguration(locations = {"classpath:config/xml/spring-context.xml"}) public class RedisTest extends AbstractJUnit4SpringContextTests { @Autowired private IUserDao userDao; /** * 新增 */ @Test public void testAddUser() { User user = new User(); user.setId("user1"); user.setName("java2000_wl1"); boolean result = userDao.add(user); Assert.assertTrue(result); } /** * 批量新增 普通方式 */ @Test public void testAddUsers1() { List<User> list = new ArrayList<User>(); for (int i = 10; i < 50000; i++) { User user = new User(); user.setId("user" + i); user.setName("java2000_wl" + i); list.add(user); } long begin = System.currentTimeMillis(); for (User user : list) { userDao.add(user); } System.out.println(System.currentTimeMillis() - begin); } /** * 批量新增 pipeline方式 */ @Test public void testAddUsers2() { List<User> list = new ArrayList<User>(); for (int i = 50000; i < 100000; i++) { User user = new User(); user.setId("user" + i); user.setName("java2000_wl" + i); list.add(user); } long begin = System.currentTimeMillis(); boolean result = userDao.add(list); System.out.println(System.currentTimeMillis() - begin); Assert.assertTrue(result); } /** * 修改 */ @Test public void testUpdate() { User user = new User(); user.setId("user1"); user.setName("new_password"); boolean result = userDao.update(user); Assert.assertTrue(result); } /** * 获取 */ @Test public void testGetUser() { String id = "user1"; User user = userDao.get(id); Assert.assertNotNull(user); Assert.assertEquals(user.getName(), "java2000_wl1"); } /** * 通过key删除单个 */ @Test public void testDelete() { String key = "user1"; userDao.delete(key); } /** * 批量删除 */ @Test public void testDeletes() { List<String> list = new ArrayList<String>(); for (int i = 0; i < 100000; i++) { list.add("user" + i); } userDao.delete(list); } /** * 设置userDao * @param userDao the userDao to set */ public void setUserDao(IUserDao userDao) { this.userDao = userDao; } }
1.5 测试
在RedisTest.java文件上右键run as --->Run Configurations,开始测试:
测试结果: