SSM整合Redis,存取redis缓存操作

1.0把项目构建好

在这里插入图片描述

1.1 导入相关jar包

在这里插入图片描述

1.2写入mybatis-config.xml(数据库属性文件)

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/students?useUnicode=true&characterEncoding=utf-8
user=root
password=root
initialSize=10
maxActive=50
maxIdle=30
minIdle=10
maxWait=120000

1.3写入applicationcontext.xml(Spring配置文件)

<?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: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/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
	<!-- 扫描 -->
	<context:component-scan base-package="com.jbit.service"/>
	<context:component-scan base-package="com.jbit.util"/>
	<!-- 加载属性文件 -->
	<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location" value="classpath:config/database.properties"/>
	</bean>
	<!-- 配置数据源,应用dbcp连接 -->
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> 
		<!-- 连接数据库配置 -->
		<property name="driverClassName" value="${driver}"></property>
		<property name="url" value="${url}"/>
		<property name="username" value="${user}"/>
		<property name="password" value="${password}"/>
		<!-- 连接池配置 有默认值 -->
		<property name="initialSize" value="${initialSize}"/>
		<property name="maxActive" value="${maxActive}"/>
		<property name="maxIdle" value="${maxIdle}"/>
		<property name="minIdle" value="${minIdle}"/>
		<property name="maxWait" value="${maxWait}"/>
	</bean>	
	<!--SqlSessionFactoryBean:负责处理SqlSessionFactory工厂  -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!--  -->
		<property name="dataSource" ref="dataSource"/>	
		<!-- 加载主配置文件 -->
		<property name="configLocation" value="classpath:config/mybatis-config.xml"/>
		<!-- 取别名 -->
		<property name="typeAliasesPackage" value="com.jbit.entiy"/>
		<!-- 映射文件 -->
		<!-- <property name="mapperLocations" value="classpath:com/jbit/Dao/grade/*.xml"/>  -->
		<property name="mapperLocations" value="classpath:com/jbit/mapping/*.xml"/>
	</bean>
	
	<!-- redis配置 -->
	<bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="close" >
		<constructor-arg name="host" value="127.0.0.1"/>
		<constructor-arg name="port" value="6379"/>
	</bean>
	<!--  
	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
	</bean>-->
	<!-- 采用扫描的方式把持久化接口创建代理对象 -->
	<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.jbit.dao"/>
	</bean>
	<!-- 事物管理性 -->
	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource"/>
	</bean>
	<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>

1.4写入springMVC-servlet.xml(SpringMvc配置文件)

<?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:aop="http://www.springframework.org/schema/aop"
	xmlns:p="http://www.springframework.org/schema/p"
	xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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.3.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd">
	<!-- 扫描包 -->
	<mvc:annotation-driven/>
	<context:component-scan base-package="com.jbit.controller"/>
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	<!-- 数据校验 -->
	<!-- 配置验证信息 -->
	<bean id="hierarchicalMessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"/>
	<!-- 数据校验器-->
	<bean id="smartValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
		<property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
		<property name="validationMessageSource" ref="hierarchicalMessageSource"/>
	</bean>
	<mvc:default-servlet-handler/>
	<!-- 文件上传 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置上传文件最大大小 -->
		<property name="maxUploadSize" value="5000000"/>
		<!-- 设置字符编码 -->
		<property name="defaultEncoding" value="UTF-8"/>
	</bean>
</beans>

1.5修改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>SSM</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>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:config/applicationcontext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	<!-- 配置springMVC -->
	<servlet>
		<!-- 在同一目录下配置 -->
		<servlet-name>springMVC</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 不同路径下配置 -->
		<init-param> 
 			<param-name>contextConfigLocation</param-name>
 			<param-value>classpath:config/springMVC-servlet.xml</param-value>
 	</init-param>
	</servlet>
	<servlet-mapping>
		<servlet-name>springMVC</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<filter>
		<filter-name>characterSet</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>characterSet</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

写完这些我们SSM框架就已经搭建好了,接下来我们去做redis的操作!


1.6创建Reids辅助类

package com.jbit.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
/**
 * redis辅助类
 * @author 
 *
 */
@Component
public class RedisUtil {
	@Autowired
	JedisPool pool;//创建代理对象
	public boolean presence(String key){
		Jedis jedis = pool.getResource();
		boolean bool=true;
		try {
			bool =jedis.exists(key);//进行判断
		}catch(Exception e){
			e.printStackTrace();//输出错误信息
		}finally {
			jedis.close();//释放资源
		}
		return bool;
	}
	/**
	 * 将缓存中数据进行反序列化
	 * @param key
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public <T>List<T> getObject(String key,Class<T> clazz){
		Jedis jedis = pool.getResource();
		ByteArrayInputStream is=null;
		ObjectInputStream ois=null;
		try {
			//将缓存中数据存入byte数组中
			byte[] b = jedis.get(key.getBytes());
			is= new ByteArrayInputStream(b);
			ois = new ObjectInputStream(is);
			return(List<T>)ois.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				is.close();
				ois.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			jedis.close();
		}
		return null;
	}
	/**
	 * 将对象进行序列化存入redis中
	 * @param object
	 * @param key
	 */
	public void saveObject(Object object,String key){
		Jedis jedis=pool.getResource();
		ByteArrayOutputStream os=null;
		ObjectOutputStream oos=null;
		try {
			os=new ByteArrayOutputStream();
			oos =new ObjectOutputStream(os);
			byte[] b=os.toByteArray();
			JSON.toJSONString(b);
			jedis.set(key.getBytes(), b);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				os.close();
				oos.close();
			} catch (Exception e2) {
				e2.printStackTrace();
			}
			jedis.close();
		}
	}
	// 把List集合对象转换成json格式保存到指定的键中
	public void saveJsonArray(Object object, String key) {
		Jedis jedis = pool.getResource();
		try {
			// 格式化成Json字符串
			String array = JSON.toJSONString(object);
			jedis.set(key, array.toString()); // 存入缓存
		} finally {
			jedis.close();
		}
	}

	// 通过键取出Json字符串并转换成 <T>这个T所指定的类型
	public  <T> T getJsonArray(String key, Class<T> clazz) {
		Jedis jedis = pool.getResource();
		try {
			String str = jedis.get(key);
			// 把字符串转换回集合对象 clazz是指定的类型
			return JSON.parseObject(str, clazz);
		} finally {
			jedis.close();
		}
	}
}

1.7使用Redis辅助类操作

/**
 * 学生控制器
 * @author 
 *
 */
@Controller
@RequestMapping("/student")
public class StudentController {
	@Autowired
	StudentService service;
	@Autowired
	GradeService grade;
	@Autowired
	JedisPool pool;//创建代理对象
	@Autowired
	RedisUtil redis;
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping("/selAll")
	public String selAll(@RequestParam(value="index",defaultValue="1",required=false) int index,Model mo,@RequestParam(defaultValue="0") int id,String name,HttpServletRequest request){
		HttpSession session = request.getSession();
		if(id!=0){
			session.setAttribute("id", id);
		}else{
			if(session.getAttribute("id")!=null){
				id=(int)session.getAttribute("id");
			}
		}
		if(name!=null){
			session.setAttribute("name",name);
		}else{
			if(session.getAttribute("name")!=null){
				name = session.getAttribute("name").toString();
			}
		}

		//分页代码
		PageUtil<Student> p =new PageUtil<Student>();
		List<Grade> gr = grade.selAll();//查询所有年级信息
		p.setPageSize(3);//页大小
		p.setPageIndex(index);//当前页
		List<Student> list = service.selPage(index, p.getPageSize(),id,name);//页数据
		p.setPagedata(list);
		p.setTotaCount(service.selCount(id,name));//总记录数
		if(p.getTotaCount()%p.getPageSize()==0){
			p.setTotaPageNumber(p.getTotaCount()/p.getPageSize());//总页数
		}else{
			p.setTotaPageNumber(p.getTotaCount()/p.getPageSize()+1);//总页数
		}
		
		//redis缓存存取促操作
		PageUtil<Student> page=null;
		if(redis.presence("page"+index)){//key值存在就中redis缓存中取出,如果不存在就存入redis中
			System.out.println("从Redis 缓存中取数据..");
			page=redis.getJsonArray("page"+index,PageUtil.class);
		}else{
			System.out.println("从数据库中取数据,并存入缓存..");
			page = p;
			redis.saveJsonArray(p, "page"+index);
		}
		
		mo.addAttribute("name",name);
		mo.addAttribute("id",id);
		mo.addAttribute("student",p);
		mo.addAttribute("grade",gr);
		return "StudentInfo";
	}
}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值