详解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 | 2天前 |
- Redis事务怎么用?4步带你快速掌握事务精髓!
- 111浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis启动不能访问?保姆级排错+解决方案
- 142浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis与RabbitMQ性能对决,这些意想不到的联合场景你压根猜不到!
- 415浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis集群分片教学:手把手教你搞定数据分片
- 126浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis防火墙规则配置教学,大佬带你玩转最佳实践
- 361浏览 收藏
-
- 数据库 · Redis | 2天前 |
- RedisvsMemcached:哪个更适合你?功能对比与场景实战
- 197浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis设置强密码+详细访问控制教程(手把手教学)
- 291浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis性能优化!手把手教你定位瓶颈+解决方案
- 380浏览 收藏
-
- 数据库 · Redis | 2天前 |
- Redis+HBase双剑合璧,教你打造超神大数据存储系统!
- 436浏览 收藏
-
- 数据库 · Redis | 2天前 |
- RedisSentinel高可用集群配置超详细教程
- 254浏览 收藏
-
- 数据库 · Redis | 2天前 |
- 手把手教你判断Redis版本该不该升级
- 244浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
-
- 茅茅虫AIGC检测
- 茅茅虫AIGC检测,湖南茅茅虫科技有限公司倾力打造,运用NLP技术精准识别AI生成文本,提供论文、专著等学术文本的AIGC检测服务。支持多种格式,生成可视化报告,保障您的学术诚信和内容质量。
- 25次使用
-
- 赛林匹克平台(Challympics)
- 探索赛林匹克平台Challympics,一个聚焦人工智能、算力算法、量子计算等前沿技术的赛事聚合平台。连接产学研用,助力科技创新与产业升级。
- 50次使用
-
- 笔格AIPPT
- SEO 笔格AIPPT是135编辑器推出的AI智能PPT制作平台,依托DeepSeek大模型,实现智能大纲生成、一键PPT生成、AI文字优化、图像生成等功能。免费试用,提升PPT制作效率,适用于商务演示、教育培训等多种场景。
- 58次使用
-
- 稿定PPT
- 告别PPT制作难题!稿定PPT提供海量模板、AI智能生成、在线协作,助您轻松制作专业演示文稿。职场办公、教育学习、企业服务全覆盖,降本增效,释放创意!
- 54次使用
-
- Suno苏诺中文版
- 探索Suno苏诺中文版,一款颠覆传统音乐创作的AI平台。无需专业技能,轻松创作个性化音乐。智能词曲生成、风格迁移、海量音效,释放您的音乐灵感!
- 60次使用
-
- Spring+Redis+RabbitMQ开发限流和秒杀项目功能
- 2023-01-01 331浏览