详解SSH框架和Redis的整合
本篇文章给大家分享《详解SSH框架和Redis的整合》,覆盖了数据库的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
一个已有的Struts+Spring+Hibernate项目,以前使用MySQL数据库,现在想把Redis也整合进去。
1. 相关Jar文件
下载并导入以下3个Jar文件:
commons-pool2-2.4.2.jar、jedis-2.3.1.jar、spring-data-redis-1.3.4.RELEASE.jar。
2. Redis配置文件
在src文件夹下面新建一个redis.properties文件,设置连接Redis的一些属性。
redis.host=127.0.0.1 redis.port=6379 redis.default.db=1 redis.timeout=100000 redis.maxActive=300 redis.maxIdle=100 redis.maxWait=1000 redis.testOnBorrow=true
再新建一个redis.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" xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"><property-placeholder location="classpath:redis.properties"></property-placeholder><bean id="propertyConfigurerRedis" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"><property name="order" value="1"></property><property name="ignoreUnresolvablePlaceholders" value="true"></property><property name="systemPropertiesMode" value="1"></property><property name="searchSystemEnvironment" value="true"></property><property name="locations"><list><value>classpath:redis.properties</value></list></property></bean><bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"><property name="maxIdle" value="${redis.maxIdle}"></property><property name="testOnBorrow" value="${redis.testOnBorrow}"></property></bean><bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"><property name="usePool" value="true"></property><property name="hostName" value="${redis.host}"></property><property name="port" value="${redis.port}"></property><property name="timeout" value="${redis.timeout}"></property><property name="database" value="${redis.default.db}"></property><constructor-arg index="0" ref="jedisPoolConfig"></constructor-arg></bean><bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate" p:connectionfactory-ref="jedisConnectionFactory"></bean><bean id="redisBase" abstract="true"><property name="template" ref="redisTemplate"></property></bean><component-scan base-package="com.school.redisclient"></component-scan></beans>
3. Redis类
新建一个com.school.redisclient包,结构如下:
接口IRedisService:
public interface IRedisService<k v> { public void set(K key, V value, long expiredTime); public V get(K key); public Object getHash(K key, String name); public void del(K key); } </k>
抽象类AbstractRedisService,主要是对RedisTemplate进行操作:
public abstract class AbstractRedisService<k v> implements IRedisService<k v> { @Autowired private RedisTemplate<k v> redisTemplate; public RedisTemplate<k v> getRedisTemplate() { return redisTemplate; } public void setRedisTemplate(RedisTemplate<k v> redisTemplate) { this.redisTemplate = redisTemplate; } @Override public void set(final K key, final V value, final long expiredTime) { BoundValueOperations<k v> valueOper = redisTemplate.boundValueOps(key); if (expiredTime valueOper = redisTemplate.boundValueOps(key); return valueOper.get(); } @Override public Object getHash(K key, String name){ Object res = redisTemplate.boundHashOps(key).get(name); return res; } @Override public void del(K key) { if (redisTemplate.hasKey(key)) { redisTemplate.delete(key); } } } </k></k></k></k></k></k>
实现类RedisService:
@Service("redisService") public class RedisService extends AbstractRedisService<string string> { }</string>
工具类RedisTool:
public class RedisTool { private static ApplicationContext factory; private static RedisService redisService; public static ApplicationContext getFactory(){ if (factory == null){ factory = new ClassPathXmlApplicationContext("classpath:redis.xml"); } return factory; } public static RedisService getRedisService(){ if (redisService == null){ redisService = (RedisService) getFactory().getBean("redisService"); } return redisService; } }
4. 查询功能的实现
新建一个Action:RClasQueryAction,返回Redis里面所有的课程数据。
@SuppressWarnings("serial") public class RClasQueryAction extends ActionSupport { RedisService rs = RedisTool.getRedisService(); List<clas> claslist = new ArrayList<clas>(); Clas c; public String execute(){ if (rs != null){ System.out.println("RedisService : " + rs); getAllClas(); } ServletActionContext.getRequest().setAttribute("claslist", claslist); return SUCCESS; } private void getAllClas(){ claslist = new ArrayList<clas>(); int num = Integer.parseInt(rs.get("clas:count")); for (int i=0; i<num i string cid="clas:" c="new" clas int id="Integer.parseInt(String.valueOf(rs.getHash(cid," c.setid system.out.println name="(String)" rs.gethash c.setname comment="(String)" c.setcomment claslist.add><p>Struts的设置和jsp文件就不详细讲了。</p> <p><span style="color: #ff0000"><strong>5. Redis数据库</strong></span></p> <p>Redis数据库里面的内容(使用的是Redis Desktop Manager):</p> <p><img alt="" style="max-width:100%" style="max-width:100%" src="/uploads/20230101/167254475863b101f6985b6.png"></p> <p>最后是运行结果:</p> <p><img alt="" src="/uploads/20230101/167254475863b101f6dcf55.png"></p> <p>当然,这只是实现了从Redis查询数据,还没有实现将Redis作为MySQL的缓存。<br></p> <p><span style="color: #ff0000"><strong>5. 添加功能的实现</strong></span></p> <p>新建一个Action:RClasAction,实现向Redis添加课程数据,并同步到MySQL。</p> <pre class="brush:java;"> package com.school.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; import com.school.entity.Clas; import com.school.redisclient.RedisService; import com.school.redisclient.RedisTool; import com.school.service.ClasService; @SuppressWarnings("serial") public class RClasAction extends ActionSupport { @Autowired private ClasService clasService; RedisService rs = RedisTool.getRedisService(); List<clas> claslist = new ArrayList<clas>(); private Clas clas; public Clas getClas() { return clas; } public void setClas(Clas Clas) { this.clas = Clas; } public String execute(){ saveClas(clas); return SUCCESS; } @SuppressWarnings({ "rawtypes", "unchecked" }) private void saveClas(Clas c){ List<string> ids = rs.getList("clas:id"); // clas:id int num = ids.size(); int id = Integer.parseInt(ids.get(num-1)) + 1; rs.rightPushList("clas:id", String.valueOf(id)); // clas:count int count = Integer.parseInt(rs.get("clas:count")); rs.set("clas:count", String.valueOf(count+1), -1); // 增加 HashMap hashmap = new HashMap(); hashmap.put("ID", String.valueOf(id)); hashmap.put("NAME", clas.getName()); hashmap.put("COMMENT", clas.getComment()); rs.addHash("clas:" + id, hashmap); // 同步到MySQL clasService.saveClas(clas); } }</string></clas></clas>
clas:id是一个List类型的Key-Value,记录了所有的课程ID,取出最后一个ID,再+1,作为增加的课程的ID,同时clas:count的值也要+1。使用addHash()方法向Redis添加了一个Hash类型的Key-Value(也就是一门课程):
@SuppressWarnings({ "unchecked", "rawtypes" }) public synchronized void addHash(K key, HashMap map){ redisTemplate.opsForHash().putAll(key, map); }
同时将该门课程增加到MySQL。
6. 删除功能的实现
新建一个Action:RClasDeleteAction,实现删除Redis的课程数据,并同步到MySQL。
package com.school.action; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; import com.school.redisclient.RedisService; import com.school.redisclient.RedisTool; import com.school.service.ClasService; @SuppressWarnings("serial") public class RClasDeleteAction extends ActionSupport { @Autowired private ClasService clasService; RedisService rs = RedisTool.getRedisService() private int id; public int getId(){ return id; } public void setId(int id){ this.id=id; } public String execute(){ deleteClas(id); // 同步到MySQL clasService.deleteClas(id); return SUCCESS; } private void deleteClas(int id){ // 删除 rs.del("clas:" + id); // clas:count int count = Integer.parseInt(rs.get("clas:count")); rs.set("clas:count", String.valueOf(count-1), -1); // clas:id rs.delListItem("clas:id", String.valueOf(id)); } }
直接删除clas:id,再将clas:count的值-1,这两步比较简单,复杂的是从clas:id中删除该课程的ID,使用了delListItem()方法来实现:
@Override public synchronized void delListItem(K key, V value){ redisTemplate.opsForList().remove(key, 1, value); }
redisTemplate.opsForList().remove()方法类似于LREM命令。最后在MySQL中也删除相同的课程。
7. 修改功能的实现
新建一个Action:RClasUpdateAction,实现删除Redis的课程数据,并同步到MySQL。
package com.school.action; import java.util.HashMap; import org.springframework.beans.factory.annotation.Autowired; import com.opensymphony.xwork2.ActionSupport; import com.school.entity.Clas; import com.school.redisclient.RedisService; import com.school.redisclient.RedisTool; import com.school.service.ClasService; @SuppressWarnings("serial") public class RClasUpdateAction extends ActionSupport{ @Autowired private ClasService clasService; RedisService rs = RedisTool.getRedisService(); private Clas clas; public Clas getClas() { return clas; } public void setClas(Clas clas) { this.clas = clas; } @SuppressWarnings({ "unchecked", "rawtypes" }) public String execute(){ HashMap hashmap = new HashMap(); hashmap.put("ID", String.valueOf(clas.getId())); hashmap.put("NAME", clas.getName()); hashmap.put("COMMENT", clas.getComment()); rs.putHash("clas:" + clas.getId(), hashmap); // 同步到MySQL clasService.updateClas(clas); return SUCCESS; } }
使用了putHash()方法来更新:
@SuppressWarnings({ "rawtypes", "unchecked" }) @Override public synchronized void putHash(K key, HashMap map){ redisTemplate.boundHashOps(key).putAll(map); }
同时在MySQL做相同的更新操作。
好了,本文到此结束,带大家了解了《详解SSH框架和Redis的整合》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多数据库知识!

- 上一篇
- Redis中五种数据类型简单操作

- 下一篇
- 解锁redis锁的正确姿势
-
- 想人陪的茉莉
- 细节满满,收藏了,感谢作者的这篇文章内容,我会继续支持!
- 2023-02-16 13:18:48
-
- 健康的钻石
- 这篇技术文章真及时,好细啊,太给力了,收藏了,关注up主了!希望up主能多写数据库相关的文章。
- 2023-01-28 14:46:21
-
- 无心的母鸡
- 很棒,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢楼主分享博文!
- 2023-01-20 18:54:44
-
- 爱听歌的小甜瓜
- 这篇文章真及时,很详细,很好,已加入收藏夹了,关注up主了!希望up主能多写数据库相关的文章。
- 2023-01-17 08:07:55
-
- 悲凉的胡萝卜
- 赞 ??,一直没懂这个问题,但其实工作中常常有遇到...不过今天到这,帮助很大,总算是懂了,感谢博主分享文章内容!
- 2023-01-16 16:04:34
-
- 兴奋的小笼包
- 这篇文章真是及时雨啊,细节满满,很好,已加入收藏夹了,关注作者大大了!希望作者大大能多写数据库相关的文章。
- 2023-01-07 04:23:16
-
- 数据库 · Redis | 5分钟前 |
- RedisList队列优化方法分享
- 378浏览 收藏
-
- 数据库 · Redis | 21分钟前 |
- Redis位图实现用户签到优化方案
- 322浏览 收藏
-
- 数据库 · Redis | 9小时前 |
- Redis数据安全防护全攻略
- 112浏览 收藏
-
- 数据库 · Redis | 9小时前 |
- Redis哈希技巧与实战应用
- 204浏览 收藏
-
- 数据库 · Redis | 9小时前 |
- 扩展Redis集群节点的步骤与注意事项
- 163浏览 收藏
-
- 数据库 · Redis | 10小时前 |
- 高并发Redis优化技巧分享
- 147浏览 收藏
-
- 数据库 · Redis | 10小时前 |
- Redis主从复制故障排查指南
- 477浏览 收藏
-
- 数据库 · Redis | 14小时前 |
- Redis与HBase存储方案详解
- 414浏览 收藏
-
- 数据库 · Redis | 17小时前 |
- Redis与MongoDB缓存优化方法
- 193浏览 收藏
-
- 数据库 · Redis | 22小时前 |
- Redis安全配置更新操作教程
- 313浏览 收藏
-
- 数据库 · Redis | 1天前 |
- Redis单节点迁移到集群的步骤详解
- 362浏览 收藏
-
- 数据库 · Redis | 1天前 |
- Redis原子操作实现方式及使用场景
- 300浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 511次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 498次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 千音漫语
- 千音漫语,北京熠声科技倾力打造的智能声音创作助手,提供AI配音、音视频翻译、语音识别、声音克隆等强大功能,助力有声书制作、视频创作、教育培训等领域,官网:https://qianyin123.com
- 95次使用
-
- MiniWork
- MiniWork是一款智能高效的AI工具平台,专为提升工作与学习效率而设计。整合文本处理、图像生成、营销策划及运营管理等多元AI工具,提供精准智能解决方案,让复杂工作简单高效。
- 89次使用
-
- NoCode
- NoCode (nocode.cn)是领先的无代码开发平台,通过拖放、AI对话等简单操作,助您快速创建各类应用、网站与管理系统。无需编程知识,轻松实现个人生活、商业经营、企业管理多场景需求,大幅降低开发门槛,高效低成本。
- 106次使用
-
- 达医智影
- 达医智影,阿里巴巴达摩院医疗AI创新力作。全球率先利用平扫CT实现“一扫多筛”,仅一次CT扫描即可高效识别多种癌症、急症及慢病,为疾病早期发现提供智能、精准的AI影像早筛解决方案。
- 98次使用
-
- 智慧芽Eureka
- 智慧芽Eureka,专为技术创新打造的AI Agent平台。深度理解专利、研发、生物医药、材料、科创等复杂场景,通过专家级AI Agent精准执行任务,智能化工作流解放70%生产力,让您专注核心创新。
- 97次使用
-
- Spring+Redis+RabbitMQ开发限流和秒杀项目功能
- 2023-01-01 331浏览