文章目录
一、配置文件
1.导入依赖
注意jar包版本,我出现了高版本jar包导致无法注入的问题
<!-- jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.6.2</version>
</dependency>
<!-- spring-data-redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.4.2.RELEASE</version>
</dependency>
2.spring-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-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!--<context:property-placeholder location="classpath:redis.properties"/>-->
<bean id="propertyPlaceholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:redis.properties</value>
<value>classpath:db.properties</value>
</list>
</property>
</bean>
<!--定义Redis数据连接池-->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}"></property>
<property name="minIdle" value="${redis.minIdle}"></property>
<property name="maxTotal" value="${redis.maxTotal}"></property>
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>
<property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
</bean>
<!--链接Redis连接池-->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}"></property>
<property name="port" value="${redis.port}"></property>
<!--<property name="password" value="${redis.password}"></property>-->
<property name="poolConfig" ref="poolConfig"></property>
</bean>
<!--Redis模板 RedisTemplate-->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connection-factory-ref="connectionFactory" >
<!--对各种数据进行序列化方式的选择-->
<property name="keySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
</bean>
</beans>
3.redis.properties(注意文件读取问题)
redis.maxIdle=300
redis.minIdle=100
redis.maxWaitMillis=3000
redis.testOnBorrow=true
redis.maxTotal=500
redis.host=127.0.0.1
redis.port=6379
redis.password=123456
#--------------根据需求选择下面设置------------------------------------------------
redis.timeout=3000 #超时时间:单位ms
redis.pool.maxActive=200 #最大连接数:能够同时建立的“最大链接个数”
redis.pool.maxIdle=20 #最大空闲数:空闲链接数大于maxIdle时,将进行回收
redis.pool.minIdle=5 #最小空闲数:低于minIdle时,将创建新的链接
redis.pool.maxWait=3000 #最大等待时间:单位ms
redis.pool.testOnBorrow=true #使用连接时,检测连接是否成功
redis.pool.testOnReturn=true #返回连接时,检测连接是否成功
4.web.xml文件
配置监听spring-redis.xml文件
<!-- spring监听 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml,classpath:spring-redis.xml</param-value>
</context-param>
二、工具类
1.RedisUtil.class
切记:
1.工具类需要注入spring容器
2.将RedisTemplate注入RedisUtil
@Component
public class RedisUtil {
@Resource(name = "redisTemplate")
RedisTemplate<String, Object> redisTemplate;
/**
* 获取缓存
* @param cacheKey
* @return
*/
public Object getCacheValue(String cacheKey){
return redisTemplate.execute(new RedisCallback<Object>(){
public Object doInRedis(RedisConnection redisConnection) throws DataAccessException{
return redisConnection.get(cacheKey.getBytes());
}
});
/*String cacheValue=(String)redisTemplate.opsForValue().get(cacheKey);
return cacheValue;*/
}
/**
* 设置缓存值
* @param key
* @param value
*/
public void setCacheValue(String key,byte[] value){
redisTemplate.execute(new RedisCallback<Object>() {
public Object doInRedis(RedisConnection redisConnection) throws DataAccessException{
redisConnection.set(key.getBytes(),value);
return null;
}
});
/*redisTemplate.opsForValue().set(key, value);*/
}
/**
* 设置缓存值并设置有效期
* @param key
* @param value
*/
public void setCacheValueForTime(String key,String value,long time){
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}
/**
* 删除key值
* @param key
*/
public void delCacheByKey(String key){
redisTemplate.opsForValue().getOperations().delete(key);
redisTemplate.opsForHash().delete("");
}
/**
* 获取key的有效期
* @param key
*/
public long getExpireTime(String key){
long time = redisTemplate.getExpire(key);
return time;
}
/**
* 指定时间类型---秒
* @param key
* @return
*/
public long getExpireTimeType(String key){
long time = redisTemplate.getExpire(key,TimeUnit.SECONDS);
return time;
}
/**
*
* @param key---分
* @return
*/
public long getExpireTimeTypeForMin(String key){
long time = redisTemplate.getExpire(key,TimeUnit.MINUTES);
return time;
}
/**
* 设置一个自增的数据
* @param key
* @param growthLength
*/
public void testInc(String key,Long growthLength){
redisTemplate.opsForValue().increment(key, growthLength);
}
}
2.SerializeUtil.class(序列化工具类)
package com.yan.util;
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) {
}
return null;
}
public static Object unserialize(byte[] bytes) {
ByteArrayInputStream bais = null;
try {
//反序列化
bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais);
return ois.readObject();
} catch (Exception e) {
}
return null;
}
}
三、操作
1.简单示例
实体类 实现 Serializable 接口
将RedisUtil注入controller,使用即可。
controller.java
/**
* Created by yan on 2019/2/22.
*/
@Controller
public class UserController {
@Autowired
private RedisUtil redisUtil;
@Autowired
private UserService userService;
@RequestMapping("user")
@ResponseBody
public String addUser(User user){
user.setUsId(1);user.setUsName("张三");user.setUsAge(25);
//将对象存放到Redis
byte[] users = SerializeUtil.serialize(user);
redisUtil.setCacheValue("user",users);
//将对象取出
byte[] user1 = (byte[]) redisUtil.getCacheValue("user");
User user2 = (User)SerializeUtil.unserialize(user1);
return "就这样子吧";
}
}