1. spring-boot集成Redis
1 pom.xml中添加Jedis依赖, 添加Fastjson依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.38</version>
</dependency>
2 application.properties中添加配置
#redis
redis.host=10.110.3.62
redis.port=6379
redis.timeout=10
redis.password=123
redis.poolMaxTotal=1000
redis.poolMaxIdle=500
3 创建redis
@RequestMapping("/redis/get")
@ResponseBodypublic Result<User> redisGet(){
User user = redisService.get(UserKey.getById, ""+1, User.class); return Result.success(user);}
@RequestMapping("/redis/set")
@ResponseBodypublic Result<Boolean> redisSet(){
User user = new User(); user.setId(1); user.setName("test_redis"); Boolean b = redisService.set(UserKey.getById, "1", user); String str = redisService.get(UserKey.getByName, "name", String.class); return Result.success(true);}
// 首先注入jedisPool
@AutowiredJedisPool jedisPool;
+ RedisPoolFactory生产JedisPool对象
@Servicepublic class RedisPoolFactory {
@Autowired RedisConfig redisConfig; @Bean public JedisPool JedisPoolFactory(){
JedisPoolConfig poolConfig = new JedisPoolConfig(); poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle()); poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal()); poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait()); JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getTimeout() * 1000, redisConfig.getPassword(), 0); return jp; }
}
+ RedisPoolFactory 依赖的RedisConfig
@Component@ConfigurationProperties(prefix = "redis")
public class RedisConfig {
private String host; private int port; private int timeout;//秒 private String password; private int poolMaxTotal; private int poolMaxIdle; private int poolMaxWait;//秒
// 还有对应的get/set方法
// 关键代码:jedis.setex(realKey, seconds, str);
/** * 设置对象 * @param prefix * @param key * @param value * @param <T> * @return */public <T> boolean set(KeyPrefix prefix, String key, T value){
Jedis jedis = null; try{
jedis = jedisPool.getResource(); String str = beanToString(value); if(str == null || str.length() <= 0){
return false; }
// 生成真正的key String realKey = prefix.getPrefix() + key; int seconds = prefix.expireSeconds(); if(seconds <= 0){
jedis.set(realKey, str); }else{
jedis.setex(realKey, seconds, str); }
return true; }finally {
returnToPool(jedis); }
}
public <T> T get(KeyPrefix prefix, String key, Class<T> clazz){
Jedis jedis = null; try{
jedis = jedisPool.getResource(); // 生成真正的key String realKey = prefix.getPrefix() + key; String str = jedis.get(realKey); T t = stringToBean(str, clazz); return t; }finally {
returnToPool(jedis); }
}