pom.xml 添加redis
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
application-dev.yml 添加redis配置
spring:
redis:
host: your IP
port: 6379
password: 123456
pool:
max-idle: 100
min-idle: 1
max-active: 1000
max-wait: -1
RedisConfig.java
package com.example.redis;
import java.lang.reflect.Method;
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.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
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;
@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());
return sb.toString();
}
};
}
/*
* RedisTemplate对象默认使用jdkSerializer实现序列化,如果想要更换序列化的实现方式,
* 例如使用Jackson2JsonRedisSerializer实现value的序列化, 可以进行如下配置
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(jedisConnectionFactory);
// 使用Jackson2JsonRedisSerialize 替换默认序列化
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);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
// 设置value的序列化规则
template.setValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
public CacheManager cacheManager(RedisTemplate<String, Object> redisTemplate) {
RedisCacheManager manager = new RedisCacheManager(redisTemplate);
return manager;
}
}
RedisService.java
package com.example.redis;
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.Service;
@Service
public class RedisService {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisService.class);
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
LOGGER.error("set faliure: " + e);
}
return result;
}
/**
* 写入缓存设置时效时间
*
* @param key
* @param value
* @param expire
* @return
*/
public boolean setex(final String key, Object value, Long expire) {
boolean result = false;
try {
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
operations.set(key, value, expire, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
LOGGER.error("setex faliure: " + e);
}
return result;
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
ValueOperations<String, Object> operations = redisTemplate.opsForValue();
return operations.get(key);
}
/**
* 哈希 添加
*
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* 哈希获取数据
*
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey) {
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* 列表添加
*
* @param k
* @param v
*/
public void lPush(String k, Object v) {
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* 列表获取
*
* @param k
* @param start
* @param offset
* @return
*/
public List<Object> lRange(String k, long start, long offset) {
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, start, offset);
}
/**
* 集合添加
*
* @param key
* @param value
*/
public void add(String key, Object value) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* 集合获取
*
* @param key
* @return
*/
public Set<Object> setMembers(String key) {
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
*
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key, Object value, double scoure) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
/**
* 有序集合获取
*
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
测试类RedisTest.java
package com.example.redis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.google.gson.Gson;
@RestController
@RequestMapping("redis")
public class RedisTest {
private static final Logger LOGGER = LoggerFactory.getLogger(RedisTest.class);
private Gson gson = new Gson();
@Autowired
private RedisService redisService;
@RequestMapping(value = "/get/{key}", method = RequestMethod.GET)
public String get(@PathVariable("key") String key) {
Object value = redisService.get(key);
LOGGER.info("the key is: " + key + ",the value is: " + gson.toJson(value));
return gson.toJson(value);
}
@RequestMapping(value = "/set/{key}:{value}", method = RequestMethod.GET)
public String set(@PathVariable("key") String key, @PathVariable("value") String value) {
boolean result = redisService.set(key, value);
return Boolean.toString(result);
}
@RequestMapping(value = "/hmSet/{key}:{hashKey}:{value}", method = RequestMethod.GET)
public String hmSet(@PathVariable("key") String key, @PathVariable("value") Object value,
@PathVariable("hashKey") Object hashKey) {
redisService.hmSet(key, hashKey, value);
return "true";
}
@RequestMapping(value = "/setex/{key}:{value}:{expire}", method = RequestMethod.GET)
public String setex(@PathVariable("key") String key, @PathVariable("value") String value,
@PathVariable("expire") Long expire) {
boolean result = redisService.setex(key, value, expire);
return Boolean.toString(result);
}
@RequestMapping(value = "/del/{key}", method = RequestMethod.GET)
public void del(@PathVariable("key") String key) {
redisService.remove(key);
}
/*
* @Cacheable 主要的参数:
* value 缓存的名称必须指定至少一个 例如:
* @Cacheable(value=”mycache”) 或者 @Cacheable(value={”cache1”,”cache2”}
*
* key 缓存的 key,可以为空,如果指定要按照 SpEL表达式编写,如果不指定,则缺省按照方法的所有参数进行组合 例如:
* @Cacheable(value=”testcache”,key=”#userName”)
*
* condition 缓存的条件,可以为空,使用 SpEL编写,返回 true 或者 false,只有为 true 才进行缓存 例如:
* @Cacheable(value=”testcache”,condition=”#userName.length()>2”)
*/
@RequestMapping("/annotation/{cache}")
@Cacheable(value = "springboot")
public String testAnnotation(@PathVariable("cache") String cache) {
LOGGER.info("enter the method testAnnotation");
return cache;
}
}