springboot整合Redis
1.x
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
spring.redis.database=3
spring.redis.host=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.pool.max-active=1000
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=2
spring.redis.timeout=0
package com.ucare.ucareschedule.utils;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
Map<String, Long> map = new HashMap<String, Long>();
map.put("test", 60L);
rcm.setExpires(map);
return rcm;
}
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(
Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
package com.ucare.ucareschedule.utils;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
@SuppressWarnings("unchecked")
@Component
public class RedisUtil {
private static final Logger log = LoggerFactory.getLogger(RedisUtil.class);
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
log.error("redis Set Exception", e);
}
return result;
}
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
log.error("redis Set with expireTime Exception", e);
}
return result;
}
public boolean leftPush(final String key, Object value) {
boolean result = false;
try {
ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
listops.leftPush(key, value);
result = true;
} catch (Exception e) {
log.error("leftPush",e);
}
return result;
}
public boolean rightPush(final String key, Object value) {
boolean result = false;
try {
ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
listops.rightPush(key, value);
result = true;
} catch (Exception e) {
log.error("rightPush",e);
}
return result;
}
public List<Object> getList(final String key, int start, int end) {
List<Object> result = null;
ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
result = listops.range(key, start, end);
return result;
}
public boolean setHash(final String key, Object HK, Object HV) {
boolean result = false;
try {
HashOperations<Serializable, Object, Object> hashops = redisTemplate.opsForHash();
hashops.put(key, HK, HV);
result = true;
} catch (Exception e) {
log.error("setHash",e);
}
return result;
}
public Object getHash(final String key, Object HK) {
Object result = null;
HashOperations<Serializable, Object, Object> hashops = redisTemplate.opsForHash();
result = hashops.get(key, HK);
return result;
}
public boolean setSet(final String key, Object value) {
boolean result = false;
try {
SetOperations<Serializable, Object> setops = redisTemplate.opsForSet();
setops.add(key, value);
result = true;
} catch (Exception e) {
log.error("setSet",e);
}
return result;
}
public Set<Object> getSet(final String key) {
Set<Object> result = null;
SetOperations<Serializable, Object> setops = redisTemplate.opsForSet();
result = setops.members(key);
return result;
}
public boolean sortedSet(final String key, Object value, double score) {
boolean result = false;
try {
ZSetOperations<Serializable, Object> zsetops = redisTemplate.opsForZSet();
zsetops.add(key, value, score);
result = true;
} catch (Exception e) {
log.error("sortedSet",e);
}
return result;
}
public Set<Object> getSortedSet(final String key, long start, long end) {
Set<Object> result = null;
ZSetOperations<Serializable, Object> zsetops = redisTemplate.opsForZSet();
result = zsetops.range(key, start, end);
return result;
}
}
@Autowired
private RedisUtil redisUtil;
@Test
public void edit() {
redisUtil.set("aa2", "1237eeeeezzh中89");
System.out.println(redisUtil.get("aa2"));
}
2.x
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
redis:
host: localhost
port: 6379
password: 123456
jedis:
pool:
max-active: 1000
max-wait: -1
max-idle: 10
min-idle: 2
lettuce:
pool:
max-active: 1000
max-wait: -1
max-idle: 10
min-idle: 2
shutdown-timeout: 100ms
cache:
type: redis
package net.cc.schedule.redis.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
private static final Logger lg = LoggerFactory.getLogger(RedisConfig.class);
@Autowired
private JedisConnectionFactory jedisConnectionFactory;
@Bean
@Override
public KeyGenerator keyGenerator() {
return (target, method, params) -> {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(":");
sb.append(method.getName());
for (Object obj : params) {
sb.append(":" + String.valueOf(obj));
}
String rsToUse = String.valueOf(sb);
lg.info("自动生成Redis Key -> [{}]", rsToUse);
return rsToUse;
};
}
@Bean
@Override
public CacheManager cacheManager() {
lg.info("初始化 -> [{}]", "CacheManager RedisCacheManager Start");
RedisCacheManager.RedisCacheManagerBuilder builder = RedisCacheManager
.RedisCacheManagerBuilder
.fromConnectionFactory(jedisConnectionFactory);
return builder.build();
}
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory ) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
redisTemplate.setConnectionFactory(jedisConnectionFactory);
RedisSerializer stringSerializer = new StringRedisSerializer();
redisTemplate.setKeySerializer(stringSerializer);
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.setHashKeySerializer(stringSerializer);
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Override
@Bean
public CacheErrorHandler errorHandler() {
lg.info("初始化 -> [{}]", "Redis CacheErrorHandler");
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
lg.error("Redis occur handleCacheGetError:key -> [{}]", key, e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
lg.error("Redis occur handleCachePutError:key -> [{}];value -> [{}]", key, value, e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
lg.error("Redis occur handleCacheEvictError:key -> [{}]", key, e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
lg.error("Redis occur handleCacheClearError:", e);
}
};
return cacheErrorHandler;
}
@ConfigurationProperties
class DataJedisProperties{
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.jedis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.jedis.pool.max-wait}")
private long maxWaitMillis;
@Bean
JedisConnectionFactory jedisConnectionFactory() {
lg.info("Create JedisConnectionFactory successful");
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setHostName(host);
factory.setPort(port);
factory.setTimeout(timeout);
factory.setPassword(password);
return factory;
}
@Bean
public JedisPool redisPoolFactory() {
lg.info("JedisPool init successful,host -> [{}];port -> [{}]", host, port);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
return jedisPool;
}
}
}
package net.cc.schedule.redis.impl;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import net.cc.schedule.redis.inter.RedisInter;
@SuppressWarnings("unchecked")
@Component
public class RedisImpl implements RedisInter {
private static final Logger log = LoggerFactory.getLogger(RedisImpl.class);
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
@Override
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
@Override
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
@Override
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
@Override
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
@Override
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
@Override
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
log.error("redis Set Exception", e);
}
return result;
}
@Override
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
log.error("redis Set with expireTime Exception", e);
}
return result;
}
@Override
public boolean leftPush(final String key, Object value) {
boolean result = false;
try {
ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
listops.leftPush(key, value);
result = true;
} catch (Exception e) {
log.error("leftPush", e);
}
return result;
}
@Override
public boolean rightPush(final String key, Object value) {
boolean result = false;
try {
ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
listops.rightPush(key, value);
result = true;
} catch (Exception e) {
log.error("rightPush", e);
}
return result;
}
@Override
public List<Object> getList(final String key, int start, int end) {
List<Object> result = null;
ListOperations<Serializable, Object> listops = redisTemplate.opsForList();
result = listops.range(key, start, end);
return result;
}
@Override
public boolean setHash(final String key, Object HK, Object HV) {
boolean result = false;
try {
HashOperations<Serializable, Object, Object> hashops = redisTemplate.opsForHash();
hashops.put(key, HK, HV);
result = true;
} catch (Exception e) {
log.error("setHash", e);
}
return result;
}
@Override
public Object getHash(final String key, Object HK) {
Object result = null;
HashOperations<Serializable, Object, Object> hashops = redisTemplate.opsForHash();
result = hashops.get(key, HK);
return result;
}
@Override
public boolean setSet(final String key, Object value) {
boolean result = false;
try {
SetOperations<Serializable, Object> setops = redisTemplate.opsForSet();
setops.add(key, value);
result = true;
} catch (Exception e) {
log.error("setSet", e);
}
return result;
}
@Override
public Set<Object> getSet(final String key) {
Set<Object> result = null;
SetOperations<Serializable, Object> setops = redisTemplate.opsForSet();
result = setops.members(key);
return result;
}
@Override
public boolean sortedSet(final String key, Object value, double score) {
boolean result = false;
try {
ZSetOperations<Serializable, Object> zsetops = redisTemplate.opsForZSet();
zsetops.add(key, value, score);
result = true;
} catch (Exception e) {
log.error("sortedSet", e);
}
return result;
}
@Override
public Set<Object> getSortedSet(final String key, long start, long end) {
Set<Object> result = null;
ZSetOperations<Serializable, Object> zsetops = redisTemplate.opsForZSet();
result = zsetops.range(key, start, end);
return result;
}
}
@Autowired
private RedisImpl redisUtil;
@Test
public void edit() {
redisUtil.set("aa2", "1237eeeeezzh中89");
System.out.println(redisUtil.get("aa2"));
}