1.添加依赖
<!-- springboot整合 redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
2.添加redis配置
@Configuration
public class RedisConfig
{
@Bean
@ConditionalOnMissingBean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(
@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException
{
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);
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(jackson2JsonRedisSerializer);
template.setValueSerializer(jackson2JsonRedisSerializer);
template.setHashKeySerializer(jackson2JsonRedisSerializer);
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
@Bean
@ConditionalOnMissingBean(StringRedisTemplate.class)
public StringRedisTemplate stringRedisTemplate(
@Qualifier("redisConnectionFactory") RedisConnectionFactory redisConnectionFactory)
throws UnknownHostException
{
StringRedisTemplate template = new StringRedisTemplate();
template.setConnectionFactory(redisConnectionFactory);
return template;
}
@Bean(name = "redisConnectionFactory")
@ConfigurationProperties(prefix = "spring.redis")
public RedisConnectionFactory redisConnectionFactory()
{
JedisPoolConfig jedisPoolConfig = getRedisConfig();
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setUsePool(true);
jedisConnectionFactory.setPoolConfig(jedisPoolConfig);
return jedisConnectionFactory;
}
@Bean
@ConfigurationProperties(prefix = "spring.redis.jedis.pool")
public JedisPoolConfig getRedisConfig()
{
JedisPoolConfig config = new JedisPoolConfig();
return config;
}
}
3.redis工具类
@Service
public class RedisServiceImpl implements IRedisService
{
/**
* 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(RedisServiceImpl.class);
@Autowired
private RedisTemplate redisTemplate;
/**
* <写入缓存>
*
* @param key key
* @param value value
* @return 写入是否成功
* @throws
*/
@Override
public boolean set(String key, Object value)
{
boolean result = false;
try
{
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
}
catch (Exception e)
{
LOGGER.error("", e);
}
return result;
}
/**
* <写入缓存设置时效时间>
*
* @param key key
* @param value value
* @param expireTime expireTime
* @return 写入是否成功
* @throws
*/
@Override
public boolean set(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)
{
LOGGER.error("", e);
}
return result;
}
/**
* <批量删除对应的value>
*
* @param keys keys
* @throws
*/
@Override
public void remove(String... keys)
{
for (String key : keys)
{
remove(key);
}
}
/**
* <批量删除key>
*
* @param pattern pattern
* @throws
*/
@Override
public void removePattern(String pattern)
{
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
{
redisTemplate.delete(keys);
}
}
/**
* <删除对应的value>
*
* @param key key
* @throws
*/
@Override
public void remove(String key)
{
if (exists(key))
{
redisTemplate.delete(key);
}
}
/**
* <判断缓存中是否有对应的value>
*
* @param key key
* @return 是否存在
* @throws
*/
@Override
public boolean exists(String key)
{
return redisTemplate.hasKey(key);
}
/**
* <读取缓存>
*
* @param key key
* @return 结果
* @throws
*/
@Override
public Object get(String key)
{
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
return operations.get(key);
}
/**
* <哈希添加>
*
* @param key key
* @param hashKey hashKey
* @param value value
* @throws
*/
@Override
public void hmSet(String key, Object hashKey, Object value)
{
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key, hashKey, value);
}
/**
* <哈希获取数据>
*
* @param key key
* @param hashKey hashKey
* @return 结果
* @throws
*/
@Override
public Object hmGet(String key, Object hashKey)
{
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key, hashKey);
}
/**
* <列表添加>
*
* @param k k
* @param v v
* @throws
*/
@Override
public void lPush(String k, Object v)
{
ListOperations<String, Object> list = redisTemplate.opsForList();
list.rightPush(k, v);
}
/**
* <列表获取>
*
* @param k k
* @param l l
* @param l1 l1
* @return 结果
* @throws
*/
@Override
public List<Object> lRange(String k, long l, long l1)
{
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k, l, l1);
}
/**
* <集合添加>
*
* @param key key
* @param value value
* @throws
*/
@Override
public void add(String key, Object value)
{
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key, value);
}
/**
* <集合获取>
*
* @param key key
* @return 结果
* @throws
*/
@Override
public Set<Object> setMembers(String key)
{
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* <有序集合添加>
*
* @param key key
* @param value value
* @param scoure scoure
* @throws
*/
@Override
public void zAdd(String key, Object value, double scoure)
{
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key, value, scoure);
}
/**
* <有序集合获取>
*
* @param key key
* @param scoure scoure
* @param scoure1 scoure1
* @return 结果
* @throws
*/
@Override
public Set<Object> rangeByScore(String key, double scoure, double scoure1)
{
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
4.应用实例
@Service
public class CityServiceImpl implements ICityService
{
/**
* 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(CityServiceImpl.class);
@Autowired
private IRedisService redisService;
@Autowired
private CityMapper cityMapper;
/**
* <查询cityList>
*
* @param id id
* @return cityList
* @throws
*/
@Override
public CityEntity queryCityById(String id)
{
// 从缓存中获取城市信息
String key = "city_" + id;
// 缓存存在
boolean hasKey = redisService.exists(key);
if (hasKey)
{
CityEntity cityEntityFromRedis = (CityEntity)redisService.get(key);
LOGGER.info(
"CityServiceImpl.findCityById() : 从缓存中获取了城市 >> " + cityEntityFromRedis.toString());
return cityEntityFromRedis;
}
// 从 DB 中获取城市信息
CityEntity cityEntityFromDB = cityMapper.queryCityById(id);
// 插入缓存
redisService.set(key, cityEntityFromDB);
LOGGER.info("CityServiceImpl.findCityById() : 城市插入缓存 >> " + cityEntityFromDB.toString());
return cityEntityFromDB;
}
/**
* <新增city数据>
*
* @param cityEntity cityEntity
* @return 结果
* @throws
*/
@Override
public int insertCity(CityEntity cityEntity)
{
return cityMapper.insertCity(cityEntity);
}
/**
* <更新city数据>
*
* @param cityEntity cityEntity
* @return 结果
* @throws
*/
@Override
public int updateCity(CityEntity cityEntity)
{
int result = cityMapper.updateCity(cityEntity);
// 缓存存在,删除缓存
String key = "city_" + cityEntity.getId();
boolean hasKey = redisService.exists(key);
if (hasKey)
{
redisService.remove(key);
LOGGER.info("CityServiceImpl.updateCity() : 从缓存中删除城市 >> " + cityEntity.toString());
}
return result;
}
/**
* <删除city数据>
*
* @param id id
* @return 结果
* @throws
*/
@Override
public int deleteCity(String id)
{
int result = cityMapper.deleteCity(id);
// 缓存存在,删除缓存
String key = "city_" + id;
boolean hasKey = redisService.exists(key);
if (hasKey)
{
redisService.remove(key);
LOGGER.info("CityServiceImpl.deleteCity() : 从缓存中删除城市 ID >> " + id);
}
return result;
}
}
5.controller类
@RestController
@RequestMapping("/city")
public class CityController
{
/**
* 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(CityController.class);
@Autowired
private ICityService cityService;
@PostMapping("/queryCityEntityById")
public Object queryCityEntityById(@RequestBody CityEntity cityEntity)
{
return ResultUtil.returnSuccess(cityService.queryCityById(cityEntity.getId()));
}
@PostMapping("/addCity")
public Object insertCityEntity(@RequestBody CityEntity cityEntity)
{
return ResultUtil.returnSuccess(cityService.insertCity(cityEntity));
}
@PostMapping("/updateCity")
public Object updateCityEntity(@RequestBody CityEntity cityEntity)
{
return ResultUtil.returnSuccess(cityService.updateCity(cityEntity));
}
@PostMapping("/deleteCity")
public Object deleteCityEntity(@RequestBody CityEntity cityEntity)
{
return ResultUtil.returnSuccess(cityService.deleteCity(cityEntity.getId()));
}
}
6.redis连接配置
spring:
redis:
host: localhost
port: 6379
password:
database: 1
jedis:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
timeout: 5000ms
Redis中常见的五大类数据类型:String,List,Set,Hash和ZSet。
RedisTemplate封装了方法对五大类数据进行操作,示例如下:
//针对String
RedisTemplate.opsForValue();
//针对List
RedisTemplate.opsForList();
//针对Set
RedisTemplate.opsForSet();
//针对Hash
RedisTemplate.opsForHash();
//针对ZSet
RedisTemplate.opsForZSet();
每一个方法都会返回一个Operations对象,该对象封装了该类型的一系列操作。
以opsForValue为例:
public ValueOperations<K, V> opsForValue() {
if (valueOps == null) {
valueOps = new DefaultValueOperations<K, V>(this);
}
return valueOps;
}
ValueOperations源码如下:
public interface ValueOperations<K, V> {
/**
* Set {@code value} for {@code key}.
*
* @param key must not be {@literal null}.
* @param value
* @see <a href="http://redis.io/commands/set">Redis Documentation: SET</a>
*/
void set(K key, V value);
/**
* Set the {@code value} and expiration {@code timeout} for {@code key}.
*
* @param key must not be {@literal null}.
* @param value
* @param timeout
* @param unit must not be {@literal null}.
* @see <a href="http://redis.io/commands/setex">Redis Documentation: SETEX</a>
*/
void set(K key, V value, long timeout, TimeUnit unit);
/**
* Set {@code key} to hold the string {@code value} if {@code key} is absent.
*
* @param key must not be {@literal null}.
* @param value
* @see <a href="http://redis.io/commands/setnx">Redis Documentation: SETNX</a>
*/
Boolean setIfAbsent(K key, V value);
/**
* Set multiple keys to multiple values using key-value pairs provided in {@code tuple}.
*
* @param map must not be {@literal null}.
* @see <a href="http://redis.io/commands/mset">Redis Documentation: MSET</a>
*/
void multiSet(Map<? extends K, ? extends V> map);
/**
* Set multiple keys to multiple values using key-value pairs provided in {@code tuple} only if the provided key does
* not exist.
*
* @param map must not be {@literal null}.
* @see <a href="http://redis.io/commands/mset">Redis Documentation: MSET</a>
*/
Boolean multiSetIfAbsent(Map<? extends K, ? extends V> map);
/**
* Get the value of {@code key}.
*
* @param key must not be {@literal null}.
* @see <a href="http://redis.io/commands/get">Redis Documentation: GET</a>
*/
V get(Object key);
/**
* Set {@code value} of {@code key} and return its old value.
*
* @param key must not be {@literal null}.
* @see <a href="http://redis.io/commands/getset">Redis Documentation: GETSET</a>
*/
V getAndSet(K key, V value);
/**
* Get multiple {@code keys}. Values are returned in the order of the requested keys.
*
* @param keys must not be {@literal null}.
* @see <a href="http://redis.io/commands/mget">Redis Documentation: MGET</a>
*/
List<V> multiGet(Collection<K> keys);
/**
* Increment an integer value stored as string value under {@code key} by {@code delta}.
*
* @param key must not be {@literal null}.
* @param delta
* @see <a href="http://redis.io/commands/incr">Redis Documentation: INCR</a>
*/
Long increment(K key, long delta);
/**
* Increment a floating point number value stored as string value under {@code key} by {@code delta}.
*
* @param key must not be {@literal null}.
* @param delta
* @see <a href="http://redis.io/commands/incrbyfloat">Redis Documentation: INCRBYFLOAT</a>
*/
Double increment(K key, double delta);
/**
* Append a {@code value} to {@code key}.
*
* @param key must not be {@literal null}.
* @param value
* @see <a href="http://redis.io/commands/append">Redis Documentation: APPEND</a>
*/
Integer append(K key, String value);
/**
* Get a substring of value of {@code key} between {@code begin} and {@code end}.
*
* @param key must not be {@literal null}.
* @param start
* @param end
* @see <a href="http://redis.io/commands/getrange">Redis Documentation: GETRANGE</a>
*/
String get(K key, long start, long end);
/**
* Overwrite parts of {@code key} starting at the specified {@code offset} with given {@code value}.
*
* @param key must not be {@literal null}.
* @param value
* @param offset
* @see <a href="http://redis.io/commands/setrange">Redis Documentation: SETRANGE</a>
*/
void set(K key, V value, long offset);
/**
* Get the length of the value stored at {@code key}.
*
* @param key must not be {@literal null}.
* @see <a href="http://redis.io/commands/strlen">Redis Documentation: STRLEN</a>
*/
Long size(K key);
/**
* Sets the bit at {@code offset} in value stored at {@code key}.
*
* @param key must not be {@literal null}.
* @param offset
* @param value
* @since 1.5
* @see <a href="http://redis.io/commands/setbit">Redis Documentation: SETBIT</a>
*/
Boolean setBit(K key, long offset, boolean value);
/**
* Get the bit value at {@code offset} of value at {@code key}.
*
* @param key must not be {@literal null}.
* @param offset
* @since 1.5
* @see <a href="http://redis.io/commands/setbit">Redis Documentation: GETBIT</a>
*/
Boolean getBit(K key, long offset);
RedisOperations<K, V> getOperations();
}