ssm+redis整合的一个Demo
来源:互联网 发布:哥特式lolita淘宝 编辑:程序博客网 时间:2024/06/06 02:12
这两天经过网上各种搜索,终于成功的写出了一个关于redis缓存的demo。
第一步,准备所需的jar包;
jar包版本不匹配会出现各种各样的错误,经过多次尝试,最终成功运行的jar包版本:
jedis-2.4.2.jar,
spring-data-redis-1.3.4.RELEASE.jar,
spring-data-commons-1.8.0.RELEASE.jar,
commons-pool2-2.4.2.jar,
spring相关jar包用的是4.1.7.RELEASE版本,
全部的jar包(可能有些没用,懒的去整理了)
第二步,配置redis.properties和springmvc.xml文件;
redis.properties代码如下,主要配置了MySQL数据库连接和redis连接的属性值:
username=rootpassword=rooturl=jdbc:mysql://localhost:3306/xk?characterEncoding=utf-8driverClassName=com.mysql.jdbc.Driverredis.hostName=127.0.0.1redis.port=6379redis.timeout=15000redis.usePool=trueredis.maxIdle=300redis.maxTotal=1024redis.maxWaitMillis=1000redis.testOnBorrow=true
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:aop="http://www.springframework.org/schema/aop" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring" xmlns:redis="http://www.springframework.org/schema/redis" xmlns:tx="http://www.springframework.org/schema/tx" 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/cache http://www.springframework.org/schema/cache/spring-cache-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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis-1.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"> <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="locations"> <list> <value>classpath:redis.properties</value> </list> </property> </bean> <!-- 配置数据源 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="url" value="${url}"></property> <property name="driverClassName" value="${driverClassName}"></property> <property name="username" value="${username}"></property> <property name="password" value="${password}"></property> </bean> <!-- 扫描dao --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.zh.dao"></property> </bean> <!-- 配置sqlSessionFactory --> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mapperLocations" value="classpath:com/mapper/*.xml"></property> </bean> <!-- 开启扫描 --> <context:component-scan base-package="com"></context:component-scan> <mvc:annotation-driven></mvc:annotation-driven> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> <!-- 控制一个pool最多有多少个状态为idle(空闲)的jedis实例 --> <property name="maxIdle" value="${redis.maxIdle}"></property> <!-- 控制一个pool可分配多少个jedis实例 --> <property name="maxTotal" value="${redis.maxTotal}"></property> <!-- 表示当borrow一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException --> <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property> <!-- 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的 --> <property name="testOnBorrow" value="${redis.testOnBorrow}"></property> </bean> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" destroy-method="destroy"> <property name="poolConfig" ref="jedisPoolConfig"></property> <property name="hostName" value="${redis.hostName}"></property> <property name="port" value="${redis.port}"></property> <property name="timeout" value="${redis.timeout}"></property> <property name="usePool" value="${redis.usePool}"></property> </bean> <bean id="jedisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="jedisConnectionFactory"></property> <property name="keySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="hashKeySerializer"> <bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/> </property> <property name="valueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> <property name="hashValueSerializer"> <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"/> </property> <property name="enableTransactionSupport" value="true"></property> </bean></beans>
第三步,配置web.xml文件;
web.xml文件代码如下,标签内部配置是redis:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>redisdemo</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- The front controller of this Spring Web application, responsible for handling all application requests --> <servlet> <servlet-name>springDispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/springmvc.xml</param-value> </init-param> </servlet> <!-- Map all requests to the DispatcherServlet for handling --> <servlet-mapping> <servlet-name>springDispatcherServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <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> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:/springmvc.xml</param-value> </context-param></web-app>
第四步:创建实体类、dao、service、controller类;
实例类Teacher代码如下,这里注意要实现序列化接口,否则后面用redis存取list时会报错:
package com.zh.vo;import java.io.Serializable;public class Teacher implements Serializable { /** * 实体类实现序列化接口 */ private static final long serialVersionUID = 1L; private String teacher_id; private String teacher_name; private String teacher_pwd; private int college_id; public String getTeacher_id() { return teacher_id; } public void setTeacher_id(String teacher_id) { this.teacher_id = teacher_id; } public String getTeacher_name() { return teacher_name; } public void setTeacher_name(String teacher_name) { this.teacher_name = teacher_name; } public String getTeacher_pwd() { return teacher_pwd; } public void setTeacher_pwd(String teacher_pwd) { this.teacher_pwd = teacher_pwd; } public int getCollege_id() { return college_id; } public void setCollege_id(int college_id) { this.college_id = college_id; } @Override public String toString() { return "Teacher [teacher_id=" + teacher_id + ", teacher_name=" + teacher_name + ", teacher_pwd=" + teacher_pwd + ", college_id=" + college_id + "]"; }}
创建TeacherDao接口,代码如下:
package com.zh.dao;import java.util.List;import org.apache.ibatis.annotations.Param;import com.zh.vo.Teacher;public interface TeacherDao { public Teacher queryTeacherByTeacher(@Param("teacher") Teacher teacher); public List<Teacher> queryAllTeachers();}
创建对应的teacherMapper.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.zh.dao.TeacherDao"> <select id="queryTeacherByTeacher" parameterType="com.zh.vo.Teacher" resultType="com.zh.vo.Teacher"> select * from teacher where teacher_name=#{teacher.teacher_name} and teacher_pwd=#{teacher.teacher_pwd} </select> <select id="queryAllTeachers" resultType="com.zh.vo.Teacher"> select * from teacher </select> </mapper>
创建teacherService接口及其实现类teacherServiceImp,其实现类代码如下:
package com.zh.service;import java.util.List;import javax.annotation.Resource;import org.springframework.stereotype.Service;import com.zh.dao.TeacherDao;import com.zh.vo.Teacher;@Service("teacherService")public class TeacherServiceImp implements TeacherService { @Resource private TeacherDao teacherDao; @Override public Teacher queryTeacherByTeacher(Teacher teacher) { // TODO Auto-generated method stub return teacherDao.queryTeacherByTeacher(teacher); } @Override public List<Teacher> queryAllTeachers() { // TODO Auto-generated method stub return teacherDao.queryAllTeachers(); }}
创建一个RedisTemplateUtil工具类,代码如下,用于操作RedisTemplate(也可以不创建,不是必须的):
package com.zh.util;import java.util.List;import java.util.Map;import java.util.Set;import javax.annotation.Resource;import org.springframework.data.redis.core.HashOperations;import org.springframework.data.redis.core.ListOperations;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.SetOperations;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Service;@Service("redisTemplateUtil")public class RedisTemplateUtil { @Resource private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue(); valueOperations.set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } public void setList(String key, List<?> value) { ListOperations<String, Object> listOperations = redisTemplate.opsForList(); listOperations.leftPush(key, value); } public Object getList(String key) { return redisTemplate.opsForList().leftPop(key); } public void setSet(String key, Set<?> value) { SetOperations<String, Object> setOperations = redisTemplate.opsForSet(); setOperations.add(key, value); } public Object getSet(String key) { return redisTemplate.opsForSet().members(key); } public void setHash(String key, Map<String, ?> value) { HashOperations<String, Object, Object> hashOperations = redisTemplate.opsForHash(); hashOperations.putAll(key, value); } public Object getHash(String key) { return redisTemplate.opsForHash().entries(key); } public void delete(String key) { redisTemplate.delete(key); } }
创建teacherController类,代码如下(如果没有创建RedisTemplateUtil类,就用RedisTemplate操作):
package com.zh.controller;import java.util.List;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import org.apache.ibatis.annotations.Param;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.zh.service.TeacherService;import com.zh.util.RedisTemplateUtil;import com.zh.vo.Teacher;@Controllerpublic class TeacherController { @Resource private TeacherService teacherService; @Resource private RedisTemplate<String, Object> redisTemplate; @Resource private RedisTemplateUtil redisTemplateUtil; @RequestMapping("/login") public String login(@Param("teacher") Teacher teacher,HttpServletRequest req) { Teacher t = teacherService.queryTeacherByTeacher(teacher); if(t!=null) { return "index"; } return "redirect:login.jsp"; } @RequestMapping("/queryAllTeachers") public String queryAllTeachers(HttpServletRequest req) { redisTemplate.opsForValue().set("test", "redisTemplate测试"); System.out.println(redisTemplate.opsForValue().get("test")); redisTemplateUtil.set("utiltest", "redisTemplateUtil测试"); System.out.println(redisTemplateUtil.get("utiltest")); List<Teacher> teacherList = (List<Teacher>) redisTemplateUtil.getList("teacherList"); if(teacherList==null||teacherList.size()<0) { System.out.println("还没有缓存,将从数据库中查询。。。"); teacherList = teacherService.queryAllTeachers(); redisTemplateUtil.setList("teacherList", teacherList); }else { System.out.println("已经有缓存了。。。"); } req.getSession().setAttribute("teacherList", teacherList); return "teacherList"; }}
一共创建了3个jsp页面,
login.jsp页面代码如下:
<body> <form action="login.action" method="post"> name:<input type="text" name="teacher_name"><br/> pwd:<input type="password" name="teacher_pwd"><br/> <input type="submit" value="login"> </form></body>
index.jsp页面代码如下:
<body> <a href="queryAllTeachers.action">查询所有</a></body>
teacherList.jsp页面如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body> <table> <tr> <td>教师编号</td> <td>教师姓名</td> <td>教师密码</td> <td>学院编号</td> </tr> <c:forEach var="teacher" items="${teacherList}"> <tr> <td>${teacher.teacher_id }</td> <td>${teacher.teacher_name }</td> <td>${teacher.teacher_pwd }</td> <td>${teacher.college_id }</td> </tr> </c:forEach> </table></body></html>
运行时需要先启动redis服务器。
最后运行结果:
demo源码:https://github.com/xsyl08/redisDemo
- ssm+redis整合的一个Demo
- SSM+Redis的小demo
- SSM整合+demo
- ssm(Mysql)+Redis的Demo
- redis整合ssm
- SSM之整合Redis
- SSM+redis整合
- SSM+Redis整合
- SSM整合redis
- SSM整合redis
- ssm整合redis
- SSM+Redis整合
- SSM整合(带demo)
- springboot整合redis缓存的小demo
- maven+ssm+redis配置demo
- SSM整合Redis实现二级缓存
- SSM框架和Redis整合
- ssh2整合的一个小Demo
- oracle查看定时器
- 大文件上传插件webupload插件
- Error during artifact deployment. See server log for details.
- use IDA7.0 debug win7x64's MS driver on win10x64
- android获取屏幕的高度和宽度
- ssm+redis整合的一个Demo
- CIO如何衡量数字化转型成功?
- c++中char *与char[]区别
- 改变radio的样式 以及radio组相关操作的jquery插件
- Angular.bind方法
- 设计模式之禅PK之结构类1
- PHP XDEBUG 远程调试获取不到SERVER_NAME
- 在windows上pycharm配置spark环境
- Java web项目01 停车管理系统实现删除用户信息(六)