SSM框架整合Redis详解

开发环境

  • 开发工具:Eclipse
  • JDK:JDK-9.0.4
  • 数据库:MySQL-8.0.12
  • 服务器:apache-tomcat-9.0.12
  • Maven:apache-maven-3.6.0
  • Redis:redis-5.0.3
  • SSM:Spring-4.3.16.RELEASE + MyBatis-3.4.6

1、创建动态web工程

 (1)工程目录结构

SSM框架整合Redis详解_第1张图片 SSM框架整合Redis详解_第2张图片

 (2)导入所需jar包

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/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>
  <groupId>com.minggroupId>
  <artifactId>ssm_redis_maven_newartifactId>
  <version>0.0.1-SNAPSHOTversion>
  <packaging>warpackaging>
  <properties>
  	<spring.version>4.3.16.RELEASEspring.version>
  	<aop.version>1.9.1aop.version>
  	<mybatis.version>3.4.6mybatis.version>
  properties>
  <dependencies>
  	
  	<dependency>
	    <groupId>org.springframeworkgroupId>
	    <artifactId>spring-coreartifactId>
	    <version>${spring.version}version>
	 dependency>
	 <dependency>
    	<groupId>org.springframeworkgroupId>
    	<artifactId>spring-aopartifactId>
    	<version>${spring.version}version>
	 dependency>
	 <dependency>
	    <groupId>org.springframeworkgroupId>
	    <artifactId>spring-webartifactId>
	    <version>${spring.version}version>
	 dependency>
	 <dependency>
	    <groupId>org.springframeworkgroupId>
	    <artifactId>spring-webmvcartifactId>
	    <version>${spring.version}version>
	 dependency>
	 <dependency>
	    <groupId>org.springframeworkgroupId>
	    <artifactId>spring-jdbcartifactId>
	    <version>${spring.version}version>
	 dependency>
	 <dependency>
	    <groupId>org.springframeworkgroupId>
	    <artifactId>spring-txartifactId>
	    <version>${spring.version}version>
	 dependency>
	 
	 <dependency>
	    <groupId>aopalliancegroupId>
	    <artifactId>aopallianceartifactId>
	    <version>1.0version>
	 dependency>
	 <dependency>
	    <groupId>org.aspectjgroupId>
	    <artifactId>aspectjweaverartifactId>
	    <version>${aop.version}version>
	 dependency>
     <dependency>
	    <groupId>org.aspectjgroupId>
	    <artifactId>aspectjrtartifactId>
	    <version>${aop.version}version>
	 dependency>
	 
	 <dependency>
	    <groupId>org.mybatisgroupId>
	    <artifactId>mybatisartifactId>
	    <version>${mybatis.version}version>
	 dependency>
	 
	 <dependency>
	    <groupId>mysqlgroupId>
	    <artifactId>mysql-connector-javaartifactId>
	    <version>8.0.13version>
	    <scope>runtimescope>
	dependency>
	
	<dependency>
	    <groupId>commons-dbcpgroupId>
	    <artifactId>commons-dbcpartifactId>
	    <version>1.4version>
	dependency>
	
	<dependency>
	    <groupId>org.mybatisgroupId>
	    <artifactId>mybatis-springartifactId>
	    <version>1.3.2version>
	dependency>
	
	<dependency>
	    <groupId>javax.servletgroupId>
	    <artifactId>jstlartifactId>
	    <version>1.2version>
	dependency>
	
	<dependency>
	    <groupId>org.slf4jgroupId>
	    <artifactId>slf4j-apiartifactId>
	    <version>1.7.25version>
	dependency>
	<dependency>
	    <groupId>log4jgroupId>
	    <artifactId>log4jartifactId>
	    <version>1.2.17version>
	dependency>
	
	<dependency>
	    <groupId>redis.clientsgroupId>
	    <artifactId>jedisartifactId>
	    <version>2.9.0version>
	dependency>
	
	<dependency>
	    <groupId>org.springframework.datagroupId>
	    <artifactId>spring-data-redisartifactId>
	    <version>1.8.11.RELEASEversion>
	dependency>
  dependencies>
project>

2、持久层实现

customer_manager数据库中customer表的构建:

Customer:
package com.ming.ssm.pojo;
import java.io.Serializable;
/**
 * 数据库(customer_manager)中表(customer)所对应的实体类(Customer)
 * @author Mr.F
 *
 */
public class Customer implements Serializable{
	private static final long serialVersionUID = 1L;
	private Long c_id;
	private String c_name;
	private String c_password;
	private String c_address;
	private String c_phone;
	private String c_email;
	public Long getC_id() {
		return c_id;
	}
	public void setC_id(Long c_id) {
		this.c_id = c_id;
	}
	public String getC_name() {
		return c_name;
	}
	public void setC_name(String c_name) {
		this.c_name = c_name;
	}
	public String getC_password() {
		return c_password;
	}
	public void setC_password(String c_password) {
		this.c_password = c_password;
	}
	public String getC_address() {
		return c_address;
	}
	public void setC_address(String c_address) {
		this.c_address = c_address;
	}
	public String getC_phone() {
		return c_phone;
	}
	public void setC_phone(String c_phone) {
		this.c_phone = c_phone;
	}
	public String getC_email() {
		return c_email;
	}
	public void setC_email(String c_email) {
		this.c_email = c_email;
	}
}
CustomerMapper:
package com.ming.ssm.mapper;
import com.ming.ssm.pojo.Customer;
/**
 * 持久层实现Mybatis框架中的Mapper接口,声名对数据库的操作方法
 * @author Mr.F
 *
 */
public interface CustomerMapper {
	Customer findCustomerById(Long id); //根据ID查询客户信息
}
CustomerMapper.xml:




<mapper namespace="com.ming.ssm.mapper.CustomerMapper">
		
	
	<select id="findCustomerById" parameterType="long" resultType="Customer">
		SELECT * FROM `customer` WHERE `c_id`= #{id}
	select>
mapper>
applicationContext-dao.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">    
   		<property name="locations">
   			<list>
   				<value>classpath:jdbc.propertiesvalue>
   				<value>classpath:jedis.propertiesvalue>
   			list>
   		property>   
	bean>
	
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="${jdbc.driver}">property>
		<property name="url" value="${jdbc.url}">property>
		<property name="username" value="${jdbc.username}">property>
		<property name="password" value="${jdbc.password}">property>
	bean>
	
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		
		<property name="dataSource" ref="dataSource" />
		
		<property name="configLocation" value="classpath:SqlMapConfig.xml" />
		
		<property name="typeAliasesPackage" value="com.ming.ssm.pojo" />
	bean>
	
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<property name="basePackage" value="com.ming.ssm.mapper" />
    bean>
beans>
SqlMapConfig.xml:


<configuration>
	
	<settings>
        <setting name="logImpl" value="STDOUT_LOGGING" />
    settings>
configuration>
jdbc.properties:
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/customer_manager?serverTimezone=CTT
jdbc.username=root
jdbc.password=1314

log4j.properties:

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger= debug, stdout

3、Redis配置

applicationContext-jedis.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
	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
	http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	<cache:annotation-driven cache-manager="cacheManager"/>
	
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 
		<property name="maxIdle" value="${jedis.maxIdle}">property>
		<property name="minIdle" value="${jedis.minIdle}">property>
	 	<property name="maxTotal" value="${jedis.maxTotal}">property>  	
	bean> 
	
    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> 
	    <property name="hostName" value="${jedis.url}">property>
	 	<property name="port" value="${jedis.port}">property> 
	 	<property name="poolConfig" ref="jedisPoolConfig">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>
	<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
    	<constructor-arg ref="jedisTemplate" />
	bean>
beans>
jedis.properties
jedis.maxIdle=30
jedis.minIdle=10
jedis.maxTotal=50
jedis.url=192.168.230.128
jedis.port=6379

4、业务层实现

CustomerService:
package com.ming.ssm.service;
import com.ming.ssm.pojo.Customer;
/**
 * 定义服务层接口
 * @author Mr.F
 *
 */
public interface CustomerService {
	Customer findCustomerById(Long id); //根据ID查询客户信息
}
CustomerServiceImpl:
package com.ming.ssm.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import com.ming.ssm.mapper.CustomerMapper;
import com.ming.ssm.pojo.Customer;
import com.ming.ssm.service.CustomerService;
/**
 * 实现服务层的CustomerService接口
 * @author Mr.F
 *
 */
@Service
public class CustomerServiceImpl implements CustomerService{	
	@Autowired
	private CustomerMapper customerMapper;
	@Override
	@Cacheable(value="cacheManager", key="'customer_id_'+#id")
	public Customer findCustomerById(Long id) {
		return customerMapper.findCustomerById(id);
	}		
}
applicationContext-service.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
	
	<context:component-scan base-package="com.ming.ssm.service"/>
beans>
applicationContext-trans.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	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
	http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">	
	
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		
		<property name="dataSource" ref="dataSource" />
	bean>
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			
			<tx:method name="save*" propagation="REQUIRED" />
			<tx:method name="insert*" propagation="REQUIRED" />
			<tx:method name="delete*" propagation="REQUIRED" />
			<tx:method name="update*" propagation="REQUIRED" />
			<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
			<tx:method name="query*" propagation="SUPPORTS" read-only="true" />
		tx:attributes>
	tx:advice>
	
	<aop:config>
		<aop:advisor advice-ref="txAdvice"
			pointcut="execution(* com.ming.ssm.service.*.*(..))" />
	aop:config>
beans>

5、控制层实现

CustomerController:
package com.ming.ssm.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ming.ssm.pojo.Customer;
import com.ming.ssm.service.CustomerService;
/**
 * 定义控制层实现类
 * @author Mr.F
 *
 */
@Controller
public class CustomerController {	
	@Autowired
	private CustomerService customerService;	
	/**
	 * 根据ID查询客户
	 * @param customer
	 * @param model
	 * @return
	 */
	@RequestMapping("findOne")
	public String findOne(Customer cus, Model model) {		
	    Customer customer = customerService.findCustomerById(cus.getC_id());
		model.addAttribute("c", customer);
		return "index";
	}
}
springmvc.xml:

<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-4.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">      
	
	<context:component-scan base-package="com.ming.ssm.controller" />	
	
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/">property>
		<property name="suffix" value=".jsp">property>
	bean>
beans>
web.xml:

<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_2_5.xsd" version="2.5">
  <display-name>ssm_redis_maven_newdisplay-name>
  <welcome-file-list>
    <welcome-file>index.htmlwelcome-file>
    <welcome-file>index.htmwelcome-file>
    <welcome-file>index.jspwelcome-file>
    <welcome-file>default.htmlwelcome-file>
    <welcome-file>default.htmwelcome-file>
    <welcome-file>default.jspwelcome-file>
  welcome-file-list>
   
  <context-param>  
	<param-name>spring.profiles.activeparam-name>  
	<param-value>devparam-value>  
  context-param>  
  <context-param>  
	<param-name>spring.profiles.defaultparam-name>  
	<param-value>devparam-value>  
  context-param>
  <context-param>  
	<param-name>spring.liveBeansView.mbeanDomainparam-name>  
	<param-value>devparam-value>  
  context-param>  
  
  <context-param>
	<param-name>contextConfigLocationparam-name>
	<param-value>classpath:spring/applicationContext-*.xmlparam-value>
  context-param>
  
  <listener>
	<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  
  <filter>
	<filter-name>encodingfilter-name>
	<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
	
	<init-param>
		<param-name>encodingparam-name>
		<param-value>UTF-8param-value>
	init-param>
  filter>
  <filter-mapping>
	<filter-name>encodingfilter-name>
	<url-pattern>/*url-pattern>
  filter-mapping>
  
  <servlet>
	<servlet-name>springmvc-webservlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
	
	<init-param>
		<param-name>contextConfigLocationparam-name>
		<param-value>classpath:spring/springmvc.xmlparam-value>
	init-param>
  servlet>
  <servlet-mapping>
	<servlet-name>springmvc-webservlet-name>
	<url-pattern>*.actionurl-pattern>
  servlet-mapping>
web-app>
index.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>客户管理页面title>
head>
<body>
	<h2 align="center">客户管理系统h2>
	<form action="${pageContext.request.contextPath }/findOne.action" method="post">
		<table border="1px" align="center" width="700px">
			<tr>
				<td colspan="6" align="right">
					请输入客户ID:<input type="text" name="c_id"/>
					<input type="submit" value="查询"/>
				td>
			tr>
			<tr align="center">
				<td>客户IDtd>
				<td>客户姓名td>
				<td>客户密码td>
				<td>客户地址td>
				<td>客户手机td>
				<td>客户邮箱td>
			tr>
			<tr align="center">
				<td>${c.c_id}td>
	            <td>${c.c_name}td>
	            <td>${c.c_password}td>
		        <td>${c.c_address }td>
		        <td>${c.c_phone }td>
		        <td>${c.c_email }td>
			tr>	
		table>
	form>
body>
html>

6、工程测试

  将ssm_customer项目工程发布到本地tomcat服务器上,在浏览器地址栏访问http://localhost:8080/ssm_redis_maven_new/index.jsp,其结果如下:

SSM框架整合Redis详解_第3张图片

然后输入客户ID:3,点击 “查询” 按钮,其结果如下:

SSM框架整合Redis详解_第4张图片

由于首次查询,Redis中没有缓存数据,可以在Console控制台看到客户端发送查询语句到MySQL数据库,数据返回显示并存储到Redis缓存中:

SSM框架整合Redis详解_第5张图片 SSM框架整合Redis详解_第6张图片

再次输入客户ID:3,点击 “查询” 按钮,可以看到所查询的客户信息,并且可以在控制台看到没有MySQL数据库查询信息,这是由于Redis缓存中保存着首次查的数据。

你可能感兴趣的:(非关系型数据库,SSM,Redis)