详解SSH框架和Redis的整合
发布时间 - 2026-01-11 00:22:10 点击率:次一个已有的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做相同的更新操作。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
# ssh整合redis教程
# ssh整合redis
# ssh
# redis
# JSP 开发SSH整合异常解决办法
# MyEclipse整合ssh三大框架环境搭载用户注册源码下载
# SSH框架网上商城项目第7战之整合Struts2和Json
# SSH框架网上商城项目第1战之整合Struts2、Hibernate4.3和Spring4.2
# SSH+Jquery+Ajax框架整合
# SSH整合中 hibernate托管给Spring得到SessionFactory
# 详解JAVAEE——SSH三大框架整合(spring+struts2+hibernate)
# 新建一个
# 的是
# 是一个
# 使用了
# 还没有
# 也要
# 就不
# 是从
# 这只
# 中也
# 想把
# 一门
# 讲了
# 来实现
# 类似于
# 两步
# 方法来
# 再将
# 将该
# 配置文件
相关栏目:
【
网站优化151355 】
【
网络推广146373 】
【
网络技术251813 】
【
AI营销90571 】
相关推荐:
Laravel API资源(Resource)怎么用_格式化Laravel API响应的最佳实践
javascript事件捕获机制【深入分析IE和DOM中的事件模型】
车管所网站制作流程,交警当场开简易程序处罚决定书,在交警网站查询不到怎么办?
Laravel如何使用缓存系统提升性能_Laravel缓存驱动和应用优化方案
如何安全更换建站之星模板并保留数据?
SQL查询语句优化的实用方法总结
如何获取免费开源的自助建站系统源码?
高端建站三要素:定制模板、企业官网与响应式设计优化
Laravel如何实现数据导出到PDF_Laravel使用snappy生成网页快照PDF【方案】
高防服务器租用首荐平台,企业级优惠套餐快速部署
如何用花生壳三步快速搭建专属网站?
Laravel队列由Redis驱动怎么配置_Laravel Redis队列使用教程
齐河建站公司:营销型网站建设与SEO优化双核驱动策略
Swift中swift中的switch 语句
高端网站建设与定制开发一站式解决方案 中企动力
html5如何设置样式_HTML5样式设置方法与CSS应用技巧【教程】
如何在IIS中新建站点并配置端口与IP地址?
PHP 实现电台节目表的智能时间匹配与今日/明日轮播逻辑
百度浏览器如何管理插件 百度浏览器插件管理方法
HTML5打空格有哪些误区_新手常犯的空格使用错误【技巧】
Laravel中的Facade(门面)到底是什么原理
打开php文件提示内存不足_怎么调整php内存限制【解决方案】
LinuxShell函数封装方法_脚本复用设计思路【教程】
如何确保FTP站点访问权限与数据传输安全?
C++时间戳转换成日期时间的步骤和示例代码
制作电商网页,电商供应链怎么做?
头像制作网站在线观看,除了站酷,还有哪些比较好的设计网站?
php结合redis实现高并发下的抢购、秒杀功能的实例
js代码实现下拉菜单【推荐】
如何快速搭建高效服务器建站系统?
如何快速生成凡客建站的专业级图册?
php读取心率传感器数据怎么弄_php获取max30100的心率值【指南】
音响网站制作视频教程,隆霸音响官方网站?
Laravel怎么实现微信登录_Laravel Socialite第三方登录集成
Laravel怎么使用Blade模板引擎_Laravel模板继承与Component组件复用【手册】
香港服务器部署网站为何提示未备案?
Laravel怎么判断请求类型_Laravel Request isMethod用法
阿里云高弹*务器配置方案|支持分布式架构与多节点部署
Laravel如何保护应用免受CSRF攻击?(原理和示例)
昵图网官方站入口 昵图网素材图库官网入口
如何快速搭建高效简练网站?
如何在IIS服务器上快速部署高效网站?
Laravel控制器是什么_Laravel MVC架构中Controller的作用与实践
php增删改查怎么学_零基础入门php数据库操作必知基础【教程】
Laravel Seeder填充数据教程_Laravel模型工厂Factory使用
Laravel辅助函数有哪些_Laravel Helpers常用助手函数大全
常州企业网站制作公司,全国继续教育网怎么登录?
javascript中的数组方法有哪些_如何利用数组方法简化数据处理
Laravel怎么使用Session存储数据_Laravel会话管理与自定义驱动配置【详解】
Python制作简易注册登录系统

