个人经验,需要的话可以一看

windows 64位redis下载地址

点击打开链接

首先:安装redis服务器,分别运行redis-server.exe,redis-cli.exe,并在redis-cli.exe中设置密码(如下图)

接下来进入项目,注解都在项目中,可以自己看

首先我们要新建一个缓存类RedeisCache

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;/*** * @描述: 使用第三方内存数据库Redis作为二级缓存* @版权: Copyright (c) 2017* @作者: juin* @版本: 1.0 * @创建日期: 2017年10月30日 * @创建时间: 下午8:02:57*/
public class RedisCache implements Cache
{private static Logger logger = LoggerFactory.getLogger(RedisCache.class); /** The ReadWriteLock. */ private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();private String id;public RedisCache(final String id) {  if (id == null) {throw new IllegalArgumentException("Cache instances require an ID");}logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>MybatisRedisCache:id="+id);this.id = id;}  public String getId() {return this.id;}public void putObject(Object key, Object value) {logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>putObject:"+key+"="+value);RedisUtil.getJedis().set(SerializeUtil.serialize(key.toString()), SerializeUtil.serialize(value));}public Object getObject(Object key) {Object value = SerializeUtil.unserialize(RedisUtil.getJedis().get(SerializeUtil.serialize(key.toString())));logger.debug(">>>>>>>>>>>>>>>>>>>>>>>>getObject:"+key+"="+value);return value;}public Object removeObject(Object key) {return RedisUtil.getJedis().expire(SerializeUtil.serialize(key.toString()),0);}public void clear() {RedisUtil.getJedis().flushDB();}public int getSize() {return Integer.valueOf(RedisUtil.getJedis().dbSize().toString());}public ReadWriteLock getReadWriteLock() {return readWriteLock;}}

然后需要一个工具类

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;public final class RedisUtil {// Redis服务器IPprivate static String ADDR = "127.0.0.1";// 测试服务器//private static String ADDR = "192.168.12.134";// Redis的端口号private static int PORT = 6379;// 访问密码private static String AUTH = "123456";//访问密码//可用连接实例的最大数目,默认值为8;//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。private static int MAX_ACTIVE = 1024;//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。private static int MAX_IDLE = 200;//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;private static int MAX_WAIT = 10000;private static int TIMEOUT = 10000;//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;private static boolean TEST_ON_BORROW = true;private static JedisPool jedisPool = null;/*** 初始化Redis连接池*/static {try {JedisPoolConfig config = new JedisPoolConfig();//    config.setMaxActive(MAX_ACTIVE);config.setMaxTotal(MAX_ACTIVE);config.setMaxIdle(MAX_IDLE);config.setMaxWaitMillis(MAX_WAIT);//  config.setMaxWait(MAX_WAIT);config.setTestOnBorrow(TEST_ON_BORROW);jedisPool = new JedisPool(config, ADDR, PORT, 100000, AUTH);System.out.println("redis密码");} catch (Exception e) {e.printStackTrace();}}/*** 获取Jedis实例* @return*/public synchronized static Jedis getJedis() {try {if (jedisPool != null) {Jedis resource = jedisPool.getResource();return resource;} else {return null;}} catch (Exception e) {e.printStackTrace();return null;}}/*** 释放jedis资源* @param jedis*/public static void returnResource(final Jedis jedis) {if (jedis != null) {jedisPool.returnResource(jedis);}}/*** * 判断用户是否过期* * @param jedis*/public static boolean VerifyUser(String id) {String key = RedisUtil.getJedis().get(id);if (key == null) {return false;}return true;}
}

最后是一个关于序列化的类

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;  public class SerializeUtil {  /** * 序列化 *  * @param object * @return */  public static byte[] serialize(Object object) {  ObjectOutputStream oos = null;  ByteArrayOutputStream baos = null;  try {  // 序列化  baos = new ByteArrayOutputStream();  oos = new ObjectOutputStream(baos);  oos.writeObject(object);  byte[] bytes = baos.toByteArray();  return bytes;  } catch (Exception e) {  }  return null;  }  /** * 反序列化 *  * @param bytes * @return */  public static Object unserialize(byte[] bytes) {  ByteArrayInputStream bais = null;  try {  // 反序列化  bais = new ByteArrayInputStream(bytes);  ObjectInputStream ois = new ObjectInputStream(bais);  return ois.readObject();  } catch (Exception e) {  }  return null;  }  }

配置文件自然也是少不了的

首先是spring-redis配置文件

spring-redis:

<?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:p="http://www.springframework.org/schema/p"xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/txhttp://www.springframework.org/schema/tx/spring-tx-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><context:property-placeholder location="classpath:*.properties"/><!--设置数据池--><bean id="poolConfig"  class="redis.clients.jedis.JedisPoolConfig"><property name="maxIdle" value="${redis.maxIdle}"></property><property name="minIdle" value="${redis.minIdle}"></property><property name="maxTotal" value="${redis.maxTotal}"></property><property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property><property name="testOnBorrow" value="${redis.testOnBorrow}"></property></bean><!--链接redis--><bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"><property name="hostName" value="${redis.host}"></property><property name="port" value="${redis.port}"></property><property name="password" value="${redis.password}"></property><property name="poolConfig" ref="poolConfig"></property></bean><bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="connectionFactory" ><!--以下针对各种数据进行序列化方式的选择--><property name="keySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /></property><property name="valueSerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /></property><property name="hashKeySerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /></property><!--<property name="hashValueSerializer"><bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /></property>--></bean>
</beans>

propertis:

redis.maxIdle=300
redis.minIdle=100
redis.maxWaitMillis=3000
redis.testOnBorrow=true
redis.maxTotal=500
redis.host=127.0.0.1
redis.port=6379
redis.password=123456

务必要在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/javaeehttp://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"id="WebApp_ID" version="3.0"><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mybatis.xml,classpath:spring-redis.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><!--spring配置文件路径 --><servlet><servlet-name>dispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>dispatcherServlet</servlet-name><url-pattern>*.do</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><init-param><param-name>forceEncoding</param-name><param-value>true</param-value></init-param></filter><filter-mapping><filter-name>encodingFilter</filter-name><url-pattern>/*</url-pattern></filter-mapping><session-config><session-timeout>30</session-timeout></session-config><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>

另外也是要在spring-mybatis文件里面开启一下缓存

<?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:p="http://www.springframework.org/schema/p"xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><context:component-scan base-package="com.qdu"/> <tx:annotation-driven transaction-manager="txManager" /><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="com.mysql.jdbc.Driver" /><property name="url" value="jdbc:mysql://localhost:3306/classmanagesys" /><property name="username" value="root" /><property name="password" value="118554" /><!-- 19951211 --><!-- 118554 --></bean><!-- 开启事务及redis缓存 --><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><property name="dataSource" ref="dataSource" /><property name="mapperLocations" value="classpath:com/qdu/mapping/*.xml" />
        <property name="configurationProperties">
           <props><prop key="cacheEnabled">true</prop> <prop key="lazyLoadingEnabled">false</prop> <prop key="aggressiveLazyLoading">true</prop></props></property></bean><bean id="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><tx:annotation-driven transaction-manager="txManager" /></beans>

最后一步,在映射文件下面加上一句话

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qdu.mapping.TestMapping">
    <cache type="com.qdu.cache.RedisCache"/>
   <resultMap type="com.qdu.pojo.Test" id="TestResult"><id property="studentId" column="StudentId" /><result property="studentPassword" column="StudentPassword" /><result property="studentName" column="StudentName" /></resultMap><select id="selectFromTestById" resultMap="TestResult"parameterType="int">select * from Test where StudentId = #{studentId}</select>
</mapper>

别忘了改一下配置

打开redis.windows.conf,找到 #requirepass foobared ,去掉 # ,改为requirepass 123456

测试,成功

import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;public class RedisTest {JedisPool pool;Jedis jedis;@Beforepublic void start() {// 初始化Redis连接池pool = new JedisPool(new JedisPoolConfig(), "127.0.0.1");// 从Redis连接池中获取一个连接jedis = pool.getResource();// Redis的密码,对应redis.windows.conf中的masterauthjedis.auth("123456");}/*** 添加测试*/@Testpublic void putTest() {jedis.set("user", "adwina");System.out.println(jedis.get("user"));}/*** 覆盖测试*/@Testpublic void overWriteTest() {jedis.set("user", "Juin");System.out.println(jedis.get("user"));}/*** 追加测试*/@Testpublic void appendTest() {jedis.append("user", "侯亚军");System.out.println(jedis.get("user"));}/*** 删除测试*/@Testpublic void deleteTest() {jedis.del("user");System.out.println(jedis.get("user"));// 输出结果:null}}

ssm + redis相关推荐

  1. ssm radis mysql_从零开始搭建框架SSM+Redis+Mysql(一)之摘要

    从零开始搭建框架SSM+Redis+Mysql(一)之摘要 本文章为本人实际的操作后的回忆笔记,如果有步骤错漏,希望来信307793969@qq.com或者评论指出. 本文章只体现过程,仅体现操作流程 ...

  2. ssm+redis整合(通过cache方式)

    这几天的研究ssm redis 终于进入主题了,今天参考了网上一些文章搭建了一下ssm+redis整合,特别记录下来以便以后可以查询使用,有什么不足请大牛们提点 项目架构 1.pom.xml < ...

  3. java学籍管理系统课设报告,基于SSM+Redis+LayUI的大学生学籍信息管理系统-java学生学籍信息管理系统mysql数据源...

    "基于SSM+Redis+LayUI的大学生学籍信息管理系统-java学生学籍信息管理系统mysql数据源 1.包含源程序,数据库脚本.代码和数据库脚本都有详细注释. 2.课题设计仅供参考学 ...

  4. 基于SSM + Redis的Shiro权限管理项目

    概述 本教程结合SSM(SpringMVC + Mybatis)框架讲解Shiro,讲解的内容有自定义shiro拦截器,Shiro Freemarker标签,Shiro JSP标签,权限控制讲解. 详 ...

  5. ssm+redis 如何更简洁的利用自定义注解+AOP实现redis缓存

    基于 ssm + maven + redis 使用自定义注解 利用aop基于AspectJ方式 实现redis缓存 如何能更简洁的利用aop实现redis缓存,话不多说,上demo 需求: 数据查询时 ...

  6. Java项目:课程在线学习与测试系统(java+SSM+redis+Bootstrap+Tomcat+mysql)

    源码获取:博客首页 "资源" 里下载! 基于B/S架构的课程在线学习与测试系统 启动说明 项目为maven管理,最近集成了redis,所以在运行项目是先要下载redis并启动客户端 ...

  7. maven+ssm+redis配置demo

    前言:菜鸡一枚,本来想把redis配置在aop中,结果aop一直没配置好,只好把redis部分写到service层. 希望大家有问题或者有什么改进的能给我留言. pom文件,由于参考了很多网上的方法, ...

  8. SSM+Redis的小demo

    准备ssm工程 准备好redis服务器 构建pom.xml文件,这个pom文件基本和SSM的基本一样,知识增加了几个依赖. pom.xml <project xmlns="http:/ ...

  9. 基于SSM+Redis等主流技术,精美爱奇艺后台管理项目免费送

    一. 项目简介 新年开工第一篇,壹哥先给大家带来一个福利帖,私信壹哥可以免费获取本项目完整资料哦.在领取资料之前,请先跟着壹哥看看这个项目都有哪些亮点吧. 1.项目背景 随着中国经济的稳步发展,居民人 ...

最新文章

  1. ADMT3.2迁移域用户
  2. 构建ASP.NET MVC4+EF5+EasyUI+Unity2.x注入的后台管理系统(39)-在线人数统计探讨
  3. LeetCode-35. Search Insert Position
  4. shell常见的文件属性检查
  5. Spring 基于注解(annotation)的配置之@Qualifier注解
  6. JavaOne 2012:使用HTML5和Java构建移动应用程序
  7. vue 图片资源应该如何存放并引入(public、assets)?
  8. webpack5打包普通html项目,webpack打包其他资源
  9. 产品经理适合当项目经理吗?
  10. Charles添加断点拦截请求 修改request或者修改response
  11. matlab平行线的中线,cad怎么画两条平行线的中线
  12. React Native入门-实战解析(上)
  13. md5碰撞Java_2 MD5加密 java实现
  14. wsl2+ubuntu20安装ros2遇到update问题
  15. Java 经典小题篇
  16. python报时功能_wxPython实现整点报时
  17. JVM优化及面试热点分析
  18. 《演化学习:理论和算法的进展》
  19. 安装金山WPS2013造成的HTML5 file.type值异常
  20. uos性能测试软件,国产操作系统UOS全面深度测评,安装体验教程都在这里!

热门文章

  1. 剑网3 云服务器,《剑网3》官网——次世代国风MMORPG
  2. 解决百度云主机(BCH)wordpress程序伪静态和后台打开404问题(创客互联)
  3. 《牛客刷verilog》Part I Verilog快速入门
  4. 计算机操作系统读书笔记
  5. MacBook Pro 时间机器备份(完美解决连接移动硬盘无反应)
  6. 腾讯手机管家ROOT功能分析
  7. Play Framework IV 依赖注入(DI)
  8. 格式化代码_格式化代码是什么意思
  9. 微软再曝“丑闻”:在办公室看 VR 黄片,“HoloLens 之父”即将离职!
  10. 梦次元poi进不去了_free gv video GV