Spring整合Redis
1:添加redis和jedis的maven依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.8.4.RELEASE</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
2:reids.properties配置
redis.host = 114.225.83.3
redis.port = 6379
redis.passwd = 123456
#最大能够保持idle状态的对象数
redis.maxIdle=300
#最大分配的对象数 注意:低版本的jedis该属性名称是 maxActive
redis.maxTotal=600
#当池内没有返回对象时,最大等待时间 注意:低版本的jedis该属性名称是 maxWait
redis.maxWaitMillis=1000
#当调用borrow Object方法时,是否进行有效性检查
redis.testOnBorrow=true
#超时时间
redis.timeout=100000
3:applicationContext-redis.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- redis配置文件 -->
<context:property-placeholder location="classpath:/redis.properties"
ignore-unresolvable="true" />
<!-- 配置连接池参数 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="maxTotal" value="${redis.maxTotal}" />
<property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- 配置连接工厂 -->
<bean id="connectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}" />
<property name="port" value="${redis.port}" />
<!-- 如果redis没有开启验证,password不需要配置 -->
<property name="password" value="${redis.passwd}"></property>
<property name="timeout" value="${redis.timeout}"></property>
<property name="poolConfig" ref="poolConfig" />
</bean>
<!-- 配置模版 -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<!-- key的序列化策略 -->
<property name="keySerializer">
<!-- 字符串编码,数据以string存储 -->
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"></bean>
</property>
<!-- value的序列化策略 -->
<property name="valueSerializer">
<!-- 使用JDK的序列化手段(serializable接口,ObjectInputStrean,ObjectOutputStream),数据以字节流存储 -->
<bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer"></bean>
</property>
</bean>
</beans>
3:定义模版-BaseRedis
package com.debo.redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
public abstract class BaseRedis<K, V> {
@Autowired
protected RedisTemplate<K, V> redisTemplate;
public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
this.redisTemplate = redisTemplate;
}
protected RedisSerializer<String> getRedisSerializer() {
return redisTemplate.getStringSerializer();
}
}
4:定义一个序列化对象-pojo
package com.mote.entity;
import java.io.Serializable;
public class Pojo implements Serializable{
private static final long serialVersionUID = 6703029746128139046L;
private String id;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5:redis操作接口类 -RedisService
package com.debo.redis;
import java.util.List;
import java.util.Set;
import com.mote.entity.Pojo;
public interface RedisService {
//添加
boolean add(Pojo pojo);
//批量添加
boolean add(List<Pojo> list);
//删除
void delete(String key);
//批量删除
void delete(List<String> keys);
//更新
boolean update(Pojo pojo);
//查询
Pojo get(String keyId);
//获取所有key
Set<String> getKeys();
//清空
boolean flushDB();
}
6:redis操作类-RedisServiceImpl
package com.debo.redis;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.mote.entity.Pojo;
@Service("redisService")
public class RedisServiceImpl extends BaseRedis<String, Serializable> implements RedisService
{
public boolean add(final Pojo pojo) {
ValueOperations<String, Serializable> valueOper = redisTemplate.opsForValue();
//设值,并且过期时间设为3分钟
valueOper.set(pojo.getId(), pojo, 3, TimeUnit.MINUTES);
return true;
}
public boolean add(final List<Pojo> list) {
ValueOperations<String, Serializable> valueOper = redisTemplate.opsForValue();
for (Pojo trli : list) {
valueOper.set(trli.getId(), trli);
}
return true;
}
public void delete(String key) {
redisTemplate.delete(key);
}
public void delete(List<String> keys) {
redisTemplate.delete(keys);
}
public boolean update(Pojo pojo) {
String id = pojo.getId();
if (get(id) == null) {
throw new NullPointerException("数据行不存在, key = " + id);
}
ValueOperations<String, Serializable> valueOper = redisTemplate.opsForValue();
valueOper.set(pojo.getId(), pojo);
return true;
}
public Pojo get(String keyId) {
ValueOperations<String, Serializable> operations = redisTemplate.opsForValue();
Pojo pojo = null;
try{
pojo = (Pojo)operations.get(keyId);
}catch(Exception e)
{
e.printStackTrace();
}
return pojo;
}
public Set<String> getKeys() {
return redisTemplate.keys("*");
}
public boolean flushDB() {
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
public Boolean doInRedis(RedisConnection connection)
throws DataAccessException {
connection.flushDb();
return true;
}
});
return result;
}
}
SpringBoot整合Redis
1:添加redis启动器
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
2:配置application.yml
spring:
redis:
database: 0
host: 114.215.83.3
port: 6380
password: Mote123456
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 500
min-idle: 0
lettuce:
shutdown-timeout: 0
3:配置RedisTemplate(SpringBoot在Spring容器中已经配置了RedisTemplate的bean,但是序列化方式不是我们想要的)所以下面配置自己的RedisTemplate
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用Jackson替换默认序列化(默认采用的是JDK序列化)
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(
Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
4:RedisService
import java.util.Set;
public interface RedisService {
public Set<String> keys(String keys);
public boolean expire(String key, long time);
public long getExpire(String key);
public boolean hasKey(String key);
public void del(String... key);
public Object get(String key);
public boolean set(String key, Object value);
public boolean setnx(String key, Object value);
public boolean set(String key, Object value, long time);
public boolean setnx(String key, Object value, long time);
}
5:RedisServiceImpl
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.mote.service.RedisService;
@Service("redisService")
public class RedisServiceImpl implements RedisService {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 模糊查询key
* @param keys
* keys(*)查询所有key
* keys("m"+"*") 查询m开头的key
* @return
*/
public Set<String> keys(String keys){
try {
return redisTemplate.keys(keys);
}catch (Exception e){
e.printStackTrace();
return null;
}
}
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
/**
* String型缓存获取
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* String型缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* String型缓存放入, 不存在放入,存在返回
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean setnx(String key, Object value) {
try {
redisTemplate.opsForValue().setIfAbsent(key,value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* String型缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* String型缓存放入并设置时间,不存在放入,存在返回
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean setnx(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}