Redis缓存 集成SSM框架

Java SSM 框架集成 Redis框架

1.下载 Jedis依赖

<.!-- jedis依赖 -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>

2.配置applicationContext.xml 配置文件 位置放在最前面

<!-- 连接池基本参数配置,类似数据库连接池 -->
<context:property-placeholder location="classpath:redis.properties"/>

<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="1024"/>
<property name="maxIdle" value="200" />
<property name="testOnBorrow" value="true"/>
</bean>

<!-- 连接池配置,类似数据库连接池 -->
<bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name="hostName" value="127.0.0.1"></property>
<property name="port" value="6379"></property>
<!-- <property name="password" value="${redis.pass}"></property> -->
<property name="poolConfig" ref="poolConfig"></property>
</bean>

<bean id="redisCacheTransfer" class="com.jdt.wetalk.redisUtils.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
</bean>

3.编辑Redis.properties 文件

host=127.0.0.1
port=6379
redis.pass=123456
maxIdle=200
maxActive=1024
redis.maxWait=10000
testOnBorrow=true

4.编写一些Redis的辅助类

1)。JedisClusterFactory.java

package com.jdt.wetalk.redisUtils;

import java.util.HashSet;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

public class JedisClusterFactory implements FactoryBean<JedisCluster>, InitializingBean {
private Resource addressConfig;
private String addressKeyPrefix;

private JedisCluster jedisCluster;
private Integer timeout;
private Integer maxRedirections;
private GenericObjectPoolConfig genericObjectPoolConfig;

private Pattern p = Pattern.compile("^.+[:]\\d{1,5}\\s*$");

public JedisCluster getObject() throws Exception {
return jedisCluster;
}

public Class<? extends JedisCluster> getObjectType() {
return (this.jedisCluster != null ? this.jedisCluster.getClass() : JedisCluster.class);
}

public boolean isSingleton() {
return true;
}

private Set<HostAndPort> parseHostAndPort() throws Exception {
try {
Properties prop = new Properties();
prop.load(this.addressConfig.getInputStream());

Set<HostAndPort> haps = new HashSet<HostAndPort>();
for (Object key : prop.keySet()) {

if (!((String) key).startsWith(addressKeyPrefix)) {
continue;
}

String val = (String) prop.get(key);

boolean isIpPort = p.matcher(val).matches();

if (!isIpPort) {
throw new IllegalArgumentException("ip 或 port 不合法");
}
String[] ipAndPort = val.split(":");

HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
haps.add(hap);
}

return haps;
} catch (IllegalArgumentException ex) {
throw ex;
} catch (Exception ex) {
throw new Exception("解析 jedis 配置文件失败", ex);
}
}

public void afterPropertiesSet() throws Exception {
Set<HostAndPort> haps = this.parseHostAndPort();

jedisCluster = new JedisCluster(haps, timeout, maxRedirections, genericObjectPoolConfig);

}

public void setAddressConfig(Resource addressConfig) {
this.addressConfig = addressConfig;
}

public void setTimeout(int timeout) {
this.timeout = timeout;
}

public void setMaxRedirections(int maxRedirections) {
this.maxRedirections = maxRedirections;
}

public void setAddressKeyPrefix(String addressKeyPrefix) {
this.addressKeyPrefix = addressKeyPrefix;
}

public void setGenericObjectPoolConfig(GenericObjectPoolConfig genericObjectPoolConfig) {
this.genericObjectPoolConfig = genericObjectPoolConfig;
}

}

2)。RedisCache.java

ackage com.jdt.wetalk.redisUtils;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.jedis.JedisConnection;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;

import redis.clients.jedis.exceptions.JedisConnectionException;

public class RedisCache implements Cache {
private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);

private static JedisConnectionFactory jedisConnectionFactory;

private final String id;

private final ReadWriteLock rwl = new ReentrantReadWriteLock();

public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
logger.debug("MybatisRedisCache:id=" + id);
this.id = id;
}

/**
* 清空所有缓存
*/
public void clear() {
rwl.readLock().lock();
JedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
connection.flushDb();
connection.flushAll();
logger.debug("清除缓存.......");
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
rwl.readLock().unlock();
}
}

public String getId() {
return this.id;
}

/**
* 获取缓存总数量
*/
public int getSize() {
int result = 0;
JedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
result = Integer.valueOf(connection.dbSize().toString());
logger.info("添加mybaits二级缓存数量:" + result);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
}
return result;
}

public void putObject(Object key, Object value) {
rwl.writeLock().lock();

JedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
connection.set(SerializeUtil.serialize(key), SerializeUtil.serialize(value));
logger.info("添加mybaits二级缓存key=" + key + ",value=" + value);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
rwl.writeLock().unlock();
}
}

public Object getObject(Object key) {
// 先从缓存中去取数据,先加上读锁
rwl.readLock().lock();
Object result = null;
JedisConnection connection = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = serializer.deserialize(connection.get(serializer.serialize(key)));
logger.info("命中mybaits二级缓存,value=" + result);

} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
rwl.readLock().unlock();
}
return result;
}

public Object removeObject(Object key) {
rwl.writeLock().lock();

JedisConnection connection = null;
Object result = null;
try {
connection = jedisConnectionFactory.getConnection();
RedisSerializer<Object> serializer = new JdkSerializationRedisSerializer();
result = connection.expire(serializer.serialize(key), 0);
} catch (JedisConnectionException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.close();
}
rwl.writeLock().unlock();
}
return result;
}

public static void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
System.out.println("进入了Redis的获取========");
RedisCache.jedisConnectionFactory = jedisConnectionFactory;
}

public ReadWriteLock getReadWriteLock() {
// TODO Auto-generated method stub
return rwl;
}

}

3)RedisCacheTransfer.java

package com.jdt.wetalk.redisUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

public class RedisCacheTransfer {
@Autowired
public void setJedisConnectionFactory(JedisConnectionFactory jedisConnectionFactory) {
RedisCache.setJedisConnectionFactory(jedisConnectionFactory);
}
}

4)SerializeUtil.java

4)SerializeUtil.java
package com.jdt.wetalk.redisUtils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class SerializeUtil {
/**
* 序列化
*/
public static byte[] serialize(Object object) {
ObjectOutputStream oos = null;
ByteArrayOutputStream baos = null;
try {
// 序列化
baos = new ByteArrayOutputStream();
oos = new ObjectOutputStream(baos);
oos.writeObject(object);
byte[] bytes = baos.toByteArray();
return bytes;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

/**
* 反序列化
*/
public static Object unserialize(byte[] bytes) {
if (bytes != null) {
ByteArrayInputStream bais = null;
try {
// 反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {

}
}
return null;
}
}

上面那个 applicationContext.xml 加载 Redis.properties失败 直接在 applicationContext.xml 定义了

原文地址:https://www.cnblogs.com/sansui/p/11357093.html

时间: 2024-10-08 16:28:35

Redis缓存 集成SSM框架的相关文章

maven项目 集成SSM框架

1.新建maven项目 新建项目报错是因为缺少web.xml文件 右键项目名 找到“”java EE Tools“” 会自动生成一个web.xml文件 2.根据这模板创建文件 3.在pom.xml文件中添加 <!--集成spring -->        <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-cont

SSM框架下的redis缓存

基本SSM框架搭建:http://www.cnblogs.com/fuchuanzhipan1209/p/6274358.html 配置文件部分: 第一步:加入jar包 pom.xml <!-- spring-redis实现 --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> &l

Redis 缓存 + Spring 的集成示例(转载)

1. 依赖包安装 pom.xml 加入: <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.0.RELEASE</version> </dependency> <dependency> <groupId>redis

Redis 缓存 + Spring 的集成示例(转)

<整合 spring 4(包括mvc.context.orm) + mybatis 3 示例>一文简要介绍了最新版本的 Spring MVC.IOC.MyBatis ORM 三者的整合以及声明式事务处理.现在我们需要把缓存也整合进来,缓存我们选用的是 Redis,本文将在该文示例基础上介绍 Redis 缓存 + Spring 的集成.关于 Redis 服务器的搭建请参考博客<Redhat5.8 环境下编译安装 Redis 并将其注册为系统服务>. 1. 依赖包安装 pom.xml

Redis 缓存 + Spring 的集成示例

1. 依赖包安装 pom.xml 加入: [html] view plain copy print? <!-- redis cache related.....start --> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>1.6.0.RELEASE&

SpringBoot集成Redis分布式锁以及Redis缓存

https://blog.csdn.net/qq_26525215/article/details/79182687 集成Redis 首先在pom.xml中加入需要的redis依赖和缓存依赖 <!-- 引入redis依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifa

SSM-1第一章 认识SSM框架和Redis

第一章 认识SSM框架和Redis 1.1 Spring框架 Sring理念 Ioc  控制反转  IOC是一个容器,在Spring中,它会认为一切Java资源都是JavaBean,容器的目标是管理Bean和它们之间的关系. Aop 面向切面编程 第二章 Java设计模式 2.1 java 反射技术 Java反射技术 可以配置:类的全限定名.方法和参数,完成对象的初始化,甚至是反射某些方法. 在Java中反射是通过包java.lang.reflect.*实现的. 2.1.1通过反射构建对象 pu

SSM框架集成(附源码)

简述 SSM框架的集成主要是Spring和MyBatis的集成,SpringMVC和Spring天然集成. 1.在IDEA新建一个Maven项目 图1. 创建web-app 1.2 创建确实的文件夹,结构如下 图2.文件夹结构 2.添加相关依赖 2.1 配置pom.xml <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.s

spring boot redis 缓存(cache)集成

Spring Boot 集成教程 Spring Boot 介绍 Spring Boot 开发环境搭建(Eclipse) Spring Boot Hello World (restful接口)例子 spring boot 连接Mysql spring boot配置druid连接池连接mysql spring boot集成mybatis(1) spring boot集成mybatis(2) – 使用pagehelper实现分页 spring boot集成mybatis(3) – mybatis ge