SpringMVC集成redis教程
强调内容:本教程已默认你的idea已配置好tomcat,jdk和maven等,如果没有配置或者不会,请自行先百度,配置好环境
强调内容:未避免配置文件出错,尽量文件名,包名都用我例子文件的名字,待你熟悉以后,在自行修改
1.使用开发工具
- 开发工具IDAE 2016.3.4
- spring.version–4.1.4.RELEASE
- maven–apache-maven-3.3.9
- tomcat–apache-tomcat-8.0.26
- redis版本–Redis 2.6.13
完成之后的项目目录结构截图:(图片不清楚可以选中图片,鼠标右键菜单,在新标签页中打开图片,即可查看大图。)
项目源代码打包:百度网盘 链接:http://pan.baidu.com/s/1c2xhAPa 密码:l4x9
或者移步这里下载:http://download.csdn.net/detail/u012775558/9804191?web=web
2.集成步骤
打开idea,新建工程,选择maven项目,选择sdk,勾选create from archetype,选择如图 maven-archetype-webapp,点击next:
输入GroupId和ArtifactID,点击next
勾选override,选择你的maven的settings.xml文件地址以及本地仓库地址,点击next。
输入项目名称和项目保存路径,其他默认,finish。
- 此时开始创建maven项目,等待右下角进度条走完,会自动帮我们创建一些包。
创建完毕,注意包结构(如果没有完成,观察控制台输出,看看卡在了哪个步奏,百度解决)
6. 编辑pom.xml文件。
文件内容如下,集成了Spring、log4j、jedis(java操作redis的包)、spring-data-redis(spring和redis集成的包)
<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>redisTest</groupId>
<artifactId>redisTest</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>redisTest Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- spring版本号 -->
<spring.version>4.1.4.RELEASE</spring.version>
<!-- mybatis版本号 -->
<mybatis.version>3.2.8</mybatis.version>
<!-- log4j日志文件管理包版本 -->
<slf4j.version>1.7.7</slf4j.version>
<log4j.version>1.2.17</log4j.version>
<!-- jackson包版本 -->
<jackson.version>2.5.0</jackson.version>
</properties>
<dependencies>
<!--单元测试依赖 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<!-- 表示开发的时候引入,发布的时候不会加载此包 -->
<scope>test</scope>
</dependency>
<!--spring单元测试依赖 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- springMVC核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.1.0</version>
</dependency>
</dependencies>
<build>
<finalName>redisTest</finalName>
</build>
</project>
之后点击maven projects窗口刷新按钮,自动下载jar包,等到jar包加载完毕。这一步时间根据你的网络状况和本地仓库决定,可能时间会很久
7. 配置项目jdk。点击菜单栏file–project structure,依次选择project和modules,根据图示配置,我这里都选择了jdk1.8。
同时,在file-settings–build,Execution,Deployment–Compiler–java Compiler里也要设置为jdk1.8,如下图所示:
8. 此时包结构如图所示。手动在src/main下创建java文件夹,并将其设置为sources文件夹,此时该文件夹变为蓝色。
9. 编写java代码。先手动在java文件夹创建如图所示的包,并根据图片以及下文示例代码创建相应代码。
ViewController.java
package com.springmvc.controller;
import com.springmvc.service.RedisCacheService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class ViewController {
private static final Logger logger = Logger.getLogger(ViewController.class);
@Autowired
private RedisCacheService redisCacheService;
@RequestMapping("/view")
public String view() {
logger.info("你已通过springMVC进入controller方法");
logger.info("-------存储数据---------");
redisCacheService.putSessionObject("123","wwwwwww");
logger.info("-------读取数据---------");
redisCacheService.getsessionObject("123");
logger.info("-------删除数据---------");
redisCacheService.clearSessionObject("123");
logger.info("-------删除后再次读取数据---------");
redisCacheService.getsessionObject("123");
return "index";
}
}
RedisCacheService.java
package com.springmvc.service;
public interface RedisCacheService {
/**
* 根据id缓存数据。 参数说明:id和sessionObject不允许为null或空值。 数据库若已存在同名键,则会覆盖掉
***/
public boolean putSessionObject(String id, Object sessionObject);
/**
* 根据id删除已缓存的数据。 参数说明:id不允许为null和空值
***/
public boolean clearSessionObject(String id);
/**
* 根据id获取已缓存的缓存数据。 参数说明:id不允许为null和空值
***/
public Object getsessionObject(String id);
}
RedisCacheServiceImpl.java
package com.springmvc.service.impl;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springmvc.dao.RedisCacheDao;
import com.springmvc.service.RedisCacheService;
@Service
public class RedisCacheServiceImpl implements RedisCacheService {
private static final Logger logger = Logger
.getLogger(RedisCacheServiceImpl.class);
@Autowired
private RedisCacheDao redisCacheDao;
@Override
public boolean putSessionObject(String id, Object sessionObject) {
boolean flag = false;
if (sessionObject != null && id != null && id.trim().length() > 0) {
flag = redisCacheDao.saveObject(id, sessionObject);
logger.info("数据缓存标志:" + flag);
} else {
logger.info("参数含空值或null,缓存失败" + flag);
}
return flag;
}
@Override
public boolean clearSessionObject(String id) {
boolean flag = false;
if (id != null && id.trim().length() > 0) {
flag = redisCacheDao.deleteKey(id);
logger.info("缓存清空标志:" + flag);
} else {
logger.info("参数含空值或null,清空缓存失败");
}
return flag;
}
@Override
public Object getsessionObject(String id) {
Object sessionObject = new Object();
if (id != null && id.trim().length() > 0) {
sessionObject = redisCacheDao.getObject(id);
} else {
logger.info("参数含空值或null,获取缓存失败");
}
return sessionObject;
}
}
RedisCacheDao.java
package com.springmvc.dao;
/**
* redis的dao层接口
*
* @author Juveniless
*
* ***/
public interface RedisCacheDao
{
/**
* 根据key存储object
*
* @param key 键
* @param value 要存储的对象Object
* @return boolean 存储成功或失败的标志
* ***/
public abstract boolean saveObject(String key, Object value);
/**
* 根据key获取object
*
* @param key 键
* @return Object 与key对应的object
* ***/
public abstract Object getObject(String key);
/**
* 根据key删除数据
*
* @param key 键
* @return boolean 删除成功或失败的标志
* ***/
public abstract boolean deleteKey(String key);
}
RedisCacheDaoImpl.java
package com.springmvc.dao.impl;
import com.springmvc.dao.RedisCacheDao;
import com.springmvc.utils.SerializeUtil;
import org.apache.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.io.Serializable;
/**
* redis的dao层实现
*
* @author Juveniless
*
***/
@Repository("RedisCacheDao")
public class RedisCacheDaoImpl implements RedisCacheDao {
private static final Logger logger = Logger
.getLogger(RedisCacheDaoImpl.class.getName());
static final byte[] ngHisByte = SerializeUtil.serialize("WANDA_NGHIS");
@Resource
protected RedisTemplate<Serializable, Serializable> redisTemplate;
/**
* 根据key删除数据
*
* @param key
* 键
* @return boolean 删除成功或失败的标志
***/
@Override
public boolean deleteKey(final String key) {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] keyByte = SerializeUtil.serialize(key);
Boolean flag = false;
if (connection.hExists(ngHisByte, keyByte)) {
logger.info("存在该键,执行删除");
flag = connection.hDel(ngHisByte, keyByte);
}
return flag;
}
});
return result;
}
/**
* 根据key存储object
*
* @param key
* 键
* @param value
* 要存储的对象Object
* @return boolean 存储成功或失败的标志
***/
@Override
public boolean saveObject(final String key, final Object value) {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
byte[] keyByte = SerializeUtil.serialize(key);
byte[] valueByte = SerializeUtil.serialize(value);
Boolean flag = false;
if (connection.hExists(ngHisByte, keyByte)) {
logger.info("数据已存在,先删除旧数据");
connection.hDel(ngHisByte, keyByte);
}
flag = connection.hSet(ngHisByte, keyByte, valueByte);
return flag;
}
});
return result;
}
/**
* 根据key获取object
*
* @param key
* 键
* @return Object 与key对应的object
***/
@Override
public Object getObject(final String key) {
Object result = redisTemplate.execute(new RedisCallback<Object>() {
@Override
public Object doInRedis(RedisConnection connection)
throws DataAccessException {
Object returnObject = null;
byte[] keyByte = SerializeUtil.serialize(key);
if (connection.hExists(ngHisByte, keyByte)) {
logger.info("数据存在--开始读取");
returnObject = SerializeUtil
.unserialize(connection.hGet(ngHisByte, keyByte));
} else {
logger.info("数据不存在");
}
return returnObject;
}
});
return result;
}
}
SerializeUtil.java
package com.springmvc.utils;
import org.apache.log4j.Logger;
import java.io.*;
/***
* 序列化和反序列化工具
*
* @author Juveniless
* ***/
public class SerializeUtil
{
private static final Logger logger = Logger.getLogger(SerializeUtil.class);
/**
* 序列化
*
* @param object
* @return
*/
public static byte[] serialize(Object object)
{
byte[] bytes = null;
if (object != null)
{
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try
{
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
bytes = baos.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
logger.error("序列化出现异常:", e);
}
finally
{
close(oos);
close(baos);
}
}
return bytes;
}
/**
* 反序列化
*
* @param bytes
* @return Object
*/
public static Object unserialize(byte[] bytes)
{
Object returnObject = new Object();
if (bytes != null)
{
ByteArrayInputStream bais = null;
ObjectInputStream ois = null;
try
{
// 反序列化
bais = new ByteArrayInputStream(bytes);
ois = new ObjectInputStream(bais);
returnObject = ois.readObject();
}
catch (Exception e)
{
e.printStackTrace();
logger.error("反序列化出现异常:", e);
}
finally
{
close(bais);
close(ois);
}
}
else
{
returnObject = null;
}
return returnObject;
}
/**
* 关闭io流对象
*
* @param closeable
*/
public static void close(Closeable closeable)
{
if (closeable != null)
{
try
{
closeable.close();
}
catch (Exception e)
{
e.printStackTrace();
logger.error("关闭io流对象出现异常:", e);
}
}
}
}
–
10. 编写相关配置文件。application.properties、applicationContext.xml、log4j.properties、spring-servlet.xml、web.xml。
重点内容:注意相关配置文件的路径,前几个配置文件在resources文件夹,web.xml文件在webapp——WEB-INF文件夹
application.properties
# Redis settings
redis.host=127.0.0.1
redis.port=6379
redis.pass=
redis.maxIdle=300
redis.maxActive=600
redis.maxWait=1000
redis.testOnBorrow=true
applicationContext.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:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
">
<context:property-placeholder
ignore-resource-not-found="true" location="classpath*:application.properties" />
<!-- redis缓存数据库的相关配置 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxActive" value="${redis.maxActive}" />
<property name="maxWait" value="${redis.maxWait}" />
<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.StringRedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
</bean>
</beans>
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
log4j.appender.ROLLING_FILE.Threshold=DEBUG
log4j.appender.ROLLING_FILE.File=patientView.log
log4j.appender.ROLLING_FILE.Append=true
log4j.appender.ROLLING_FILE.MaxFileSize=10240KB
log4j.appender.ROLLING_FILE.MaxBackupIndex=20
log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=info, stdout, ROLLING_FILE
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: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-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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
<!-- 开启注解模式驱动 -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 扫包 -->
<context:component-scan base-package="com.springmvc.*"></context:component-scan>
<!-- 静态资源过滤 -->
<mvc:resources location="/resources/" mapping="/resources/**"/>
<!-- 视图渲染 jsp/freemaker/velocity-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 制定页面存放的路径 -->
<property name="prefix" value="/WEB-INF/page/"></property>
<!-- 文件的后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
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" version="3.0">
<display-name>Demo</display-name>
<!-- Spring MVC 核心配置开始 -->
<servlet>
<servlet-name>SpringMvcDemo</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 可以通过contextConfigLocation来自定义SpringMVC配置文件的位置,如不指定,则默认在WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,
此时文件名必须为[<servlet-name>]-servlet.xml,否则会出错-->
<!--以下init-param是自定义SpringMVC的配置文件的位置 -->
<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>SpringMvcDemo</servlet-name>
<!-- 此处可以可以配置成*.do,对应struts的后缀习惯 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring MVC 核心配置结束 -->
<!--配置监听器-->
<!-- 读取Spring配置文件;applicationContext.xml -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 如果是监听多个文件,可用‘,’隔开 -->
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!--Spring监听器 ApplicationContext 载入 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 读取LOG4J配置文件;log4j.properties -->
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- 定义LOG4J监听器 -->
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<!-- Spring字符集过滤器 -->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
–
11. 在webapp–WEB-INF文件夹下创建page文件夹,用来存储jsp页面。在page文件夹下创建一个简单的jsp页面做测试用。如下图所示:
–
12. 打开redis服务,我使用本机测试,因此ip为127.0.0.1。
在测试时,记得修改application.properties配置文件,修改redis数据库地址。
–
13. 配置tomcat,运行项目。
–
14. 浏览器地址栏输入:http://localhost:8080/view
控制台输出:
–