侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

详解SSH框架和Redis的整合

Redis  /  管理员 发布于 7年前   396

一个已有的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文件。

<?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: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">   <context:property-placeholder location="classpath:redis.properties"/>   <bean id="propertyConfigurerRedis"   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">   <property name="order" value="1" />   <property name="ignoreUnresolvablePlaceholders" value="true" />   <property name="systemPropertiesMode" value="1" />   <property name="searchSystemEnvironment" value="true" />   <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 name="testOnBorrow" value="${redis.testOnBorrow}" />  </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 name="port" value="${redis.port}" />   <property name="timeout" value="${redis.timeout}" />   <property name="database" value="${redis.default.db}"></property>   <constructor-arg index="0" ref="jedisPoolConfig" />  </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"/>  </bean>   <context:component-scan base-package="com.school.redisclient" /> </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);   } 

抽象类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 <= 0) {     valueOper.set(value);    } else {     valueOper.set(value, expiredTime, TimeUnit.MILLISECONDS);    }   }   @Override   public V get(final K key) {    BoundValueOperations<K, V> 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);    }   }    } 

实现类RedisService:

@Service("redisService") public class RedisService extends AbstractRedisService<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:" + (i+1);   c = new Clas();   int id = Integer.parseInt(String.valueOf(rs.getHash(cid, "ID")));   c.setId(id);   System.out.println("ID:" + id);   String name = (String) rs.getHash(cid, "NAME");   c.setName(name);   System.out.println("NAME:" + name);   String comment = (String) rs.getHash(cid, "COMMENT");   c.setComment(comment);   System.out.println("COMMENT:" + comment);   claslist.add(c);  } }}

Struts的设置和jsp文件就不详细讲了。

5. Redis数据库

Redis数据库里面的内容(使用的是Redis Desktop Manager):

最后是运行结果:

当然,这只是实现了从Redis查询数据,还没有实现将Redis作为MySQL的缓存。

5. 添加功能的实现

新建一个Action:RClasAction,实现向Redis添加课程数据,并同步到MySQL。

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); }}

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做相同的更新操作。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。


  • 上一条:
    浅谈redis的maxmemory设置以及淘汰策略
    下一条:
    详谈redis优化配置和redis.conf说明(推荐)
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在Redis中能实现的功能、常见应用介绍(0个评论)
    • 2024年Redis面试题之一(0个评论)
    • 在redis缓存常见出错及解决方案(0个评论)
    • 在redis中三种特殊数据类型:地理位置、基数(cardinality)估计、位图(Bitmap)使用场景介绍浅析(2个评论)
    • Redis 删除 key用 del 和 unlink 有啥区别?(1个评论)
    • 近期文章
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • Laravel从Accel获得5700万美元A轮融资(0个评论)
    • 在go + gin中gorm实现指定搜索/区间搜索分页列表功能接口实例(0个评论)
    • 在go语言中实现IP/CIDR的ip和netmask互转及IP段形式互转及ip是否存在IP/CIDR(0个评论)
    • PHP 8.4 Alpha 1现已发布!(0个评论)
    • Laravel 11.15版本发布 - Eloquent Builder中添加的泛型(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2017-12
    • 2020-03
    • 2020-05
    • 2021-04
    • 2022-03
    • 2022-05
    • 2022-08
    • 2023-02
    • 2023-04
    • 2023-07
    • 2024-01
    • 2024-02
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客