当前位置:首页 > 文章列表 > 数据库 > Redis > 详解SSH框架和Redis的整合

详解SSH框架和Redis的整合

来源:脚本之家 2023-01-01 11:31:21 0浏览 收藏

本篇文章给大家分享《详解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学习网公众号,给大家分享更多数据库知识!

版本声明
本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
Redis中五种数据类型简单操作Redis中五种数据类型简单操作
上一篇
Redis中五种数据类型简单操作
解锁redis锁的正确姿势
下一篇
解锁redis锁的正确姿势
查看更多
最新文章
查看更多
课程推荐
  • 前端进阶之JavaScript设计模式
    前端进阶之JavaScript设计模式
    设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
    543次学习
  • GO语言核心编程课程
    GO语言核心编程课程
    本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
    516次学习
  • 简单聊聊mysql8与网络通信
    简单聊聊mysql8与网络通信
    如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
    500次学习
  • JavaScript正则表达式基础与实战
    JavaScript正则表达式基础与实战
    在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
    487次学习
  • 从零制作响应式网站—Grid布局
    从零制作响应式网站—Grid布局
    本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
    485次学习
查看更多
AI推荐
  • ChatExcel酷表:告别Excel难题,北大团队AI助手助您轻松处理数据
    ChatExcel酷表
    ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
    3161次使用
  • Any绘本:开源免费AI绘本创作工具深度解析
    Any绘本
    探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
    3374次使用
  • 可赞AI:AI驱动办公可视化智能工具,一键高效生成文档图表脑图
    可赞AI
    可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
    3402次使用
  • 星月写作:AI网文创作神器,助力爆款小说速成
    星月写作
    星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
    4505次使用
  • MagicLight.ai:叙事驱动AI动画视频创作平台 | 高效生成专业级故事动画
    MagicLight
    MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
    3783次使用
微信登录更方便
  • 密码登录
  • 注册账号
登录即同意 用户协议隐私政策
返回登录
  • 重置密码