pom文件下添加配置:
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.2</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.8</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
application.yml中配置redis连接信息(根据自己的redis服务器进行更改):
spring:
redis:
lettuce:
pool:
MaxTotal: 400
minIdle: 1
maxWaitMillis: 5000
maxIdle: 30
testOnBorrow: true
testOnReturn: true
testWhileIdle: true
redis:
database: 1
hostName: 10.0.52.160
password:
port: 6379
timeout: 5000
创建redis配置类:
/**
* redis配置
*/
@Data
@Configuration
@ConfigurationProperties("redis")
public class RedisPoolConfig {
private String hostName;
private int port;
private String password;
private int database;
private int timeout;
@Bean
@ConfigurationProperties(prefix = "spring.redis.lettuce.pool")
@Scope(value = "prototype")
public GenericObjectPoolConfig poolConfig() {
return new GenericObjectPoolConfig();
}
@Bean
@Primary
public JedisPool jedisPoolDefault(GenericObjectPoolConfig poolConfig) {
if (null != password && password.length() == 0) {
password = null;
}
return new JedisPool(poolConfig, hostName, port, timeout, password, database);
}
@Bean(name = "recreationCoreRedisExecutor")
@Primary
public RedisExecutor redisExecutor(JedisPool jedisPoolDefault) {
return new JedisExecutor(jedisPoolDefault);
}
}
redis相关接口和执行器定义:
/**
* jedis执行命令,有返回值
*/
public interface JedisCallable<T> {
/**
* 使用jedis连接执行redis命令
*
* @param instance
* @return
* @throws Exception 业务异常可以自行处理
*/
T call(Jedis instance) throws Exception;
}
/**
* 使用jedis的pipleline执行redis命令
*/
public interface JedisPipelined {
/**
* 使用jedis pipeline批量执行一组redis命令
* <p>
* 注意:需要自己调用pipeline.sync()方法提交命令
*
* @param pipeline
* @throws Exception 业务异常可以自行处理
*/
void runInPipeline(Pipeline pipeline) throws Exception;
}
/**
* jedis执行命令,不带返回值
*/
public interface JedisRunnable {
/**
* 使用jedis连接执行redis命令
*
* @param instance
* @throws Exception 业务异常可以自行处理
*/
void run(Jedis instance) throws Exception;
}
/**
* Redis执行器
*/
public interface RedisExecutor {
/**
* 使用jedis执行redis命令
*/
void doInRedis(JedisRunnable runnable);
/**
* 使用jedis执行redis命令
*/
<T> T doInRedis(JedisCallable<T> callable);
/**
* 使用jedis pipeline机制批量执行redis命令
* <p>
* 请使用pipeline.sync()方法提交批量执行
* <p>
*/
void doInPipeline(JedisPipelined pipeline);
}
/**
* Jedis执行器,用来执行与Redis相关的业务逻辑
* <p>
* 业务逻辑由业务模块来写,这里只负责执行,包括异常的处理,Redis连接的分配与回收
*/
public class JedisExecutor implements RedisExecutor {
private Logger logger = LoggerFactory.getLogger(JedisExecutor.class.getName());
private JedisPool jedisPool;
public JedisExecutor(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}
private Jedis getJedis(JedisPool jedisPool) {
Jedis resource;
try {
resource = jedisPool.getResource();
} catch (JedisException e) {
logger.error("从连接池中拿Jedis连接时发生异常", e);
throw e;
}
if (resource == null) {
logger.error("从连接池中拿Jedis连接为空");
throw new IllegalStateException("从连接池中拿Jedis连接为空");
}
return resource;
}
private void finishResource(JedisPool jedisPool, Jedis resource) {
if (jedisPool == null) {
return;
}
resource.close();
}
private void logResourceInfo(Jedis resource) {
StringBuilder message = new StringBuilder();
message.append("Redis连接属性,host ip:");
message.append(resource.getClient().getHost());
message.append(",port:");
message.append(resource.getClient().getPort());
message.append(",DB:");
message.append(resource.getDB());
message.append(",ConnectionTimeout:");
message.append(resource.getClient().getConnectionTimeout());
message.append(",SoTimeout:");
message.append(resource.getClient().getSoTimeout());
logger.debug(message.toString());
}
@Override
public void doInRedis(JedisRunnable runnable) {
Jedis jedis = getJedis(jedisPool);
try {
logResourceInfo(jedis);
runnable.run(jedis);
} catch (Exception e) {
// 处理业务异常
throw new RedisRuntimeException(e);
} finally {
// 只有jedis异常才算jedis连接坏了,其它的业务异常不影响jedis连接的继续使用
finishResource(jedisPool, jedis);
}
}
@Override
public <T> T doInRedis(JedisCallable<T> callable) {
Jedis jedis = getJedis(jedisPool);
try {
logResourceInfo(jedis);
return callable.call(jedis);
} catch (Exception e) {
// 处理业务异常
throw new RedisRuntimeException(e);
} finally {
// 只有jedis异常才算jedis连接坏了,其它的业务异常不影响jedis连接的继续使用
finishResource(jedisPool, jedis);
}
}
@Override
public void doInPipeline(JedisPipelined pipelined) {
Jedis jedis = getJedis(jedisPool);
try {
logResourceInfo(jedis);
Pipeline pipeline = jedis.pipelined();
pipelined.runInPipeline(pipeline);
} catch (Exception e) {
// 处理业务异常
throw new RedisRuntimeException(e);
} finally {
// 只有jedis异常才算jedis连接坏了,其它的业务异常不影响jedis连接的继续使用
finishResource(jedisPool, jedis);
}
}
}
/**
* redis运行时异常
*/
public class RedisRuntimeException extends RuntimeException {
private static final long serialVersionUID = 1L;
public RedisRuntimeException() {
super();
}
public RedisRuntimeException(String message, Throwable cause,
boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public RedisRuntimeException(String message, Throwable cause) {
super(message, cause);
}
public RedisRuntimeException(String message) {
super(message);
}
public RedisRuntimeException(Throwable cause) {
super(cause);
}
}
创建测试控制器:
/**
* 测试Controller
*
* @author tuc
*/
@RestController
public class TestController {
@Autowired
private UserCache userCache;
/***
* 保存用户信息到redis(假设用户id=1)
*/
@PostMapping("/setCache")
public ResultModel setCache() {
try {
Map<String, Object> map = new HashMap<>(1);
UserModel user = new UserModel();
user.setId(1);
user.setName("张三");
user.setAge(18);
user.setPhone("15388888888");
userCache.cacheUserRecord(user);
map.put("user", user);
return ResultTools.result(0, "", map);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
/***
* 获取redis中缓存的用户信息
*/
@GetMapping("/getCache")
public ResultModel getCache(Integer id) {
try {
Map<String, Object> map = new HashMap<>(1);
UserModel user = userCache.getUserRecord("" + id);
map.put("user", user);
return ResultTools.result(0, "", map);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
/***
* 删除对应缓存
*/
@PostMapping("/delCache")
public ResultModel delCache(Integer id) {
try {
Map<String, Object> map = new HashMap<>(1);
userCache.delUserRecord(id + "");
return ResultTools.result(0, "", map);
} catch (Exception e) {
return ResultTools.result(404, e.getMessage(), null);
}
}
}
调用http://localhost:8080/setCache:
使用redis可视化工具查看:
可以看到数据已经存进redis中了
调用http://localhost:8080/getCache?id=1:
可以看到,正常取到了redis中对应id为1的值了
想手动删除的时候调用http://localhost:8080/delCache?id=1:
使用redis可视化工具查看:
缓存的id=1的用户信息已被删除掉了。
最后附上源码下载地址:https://download.youkuaiyun.com/download/qq_29370483/11194881