redis Demo 完美代码
程序员文章站
2022-07-12 12:28:46
...
redis配置
#redis配置
#redis.host=47.98.210.68
redis.host=localhost
redis.port=6379
redis.timeout=10
redis.password=123456
redis.poolMaxTotal=1000
redis.poolMaxIdle=500
redis.poolMaxWait=500
config配置
@Component
@ConfigurationProperties(prefix = "redis") // 读取配置文件 前缀是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; // 秒
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPoolMaxTotal() {
return poolMaxTotal;
}
public void setPoolMaxTotal(int poolMaxTotal) {
this.poolMaxTotal = poolMaxTotal;
}
public int getPoolMaxIdle() {
return poolMaxIdle;
}
public void setPoolMaxIdle(int poolMaxIdle) {
this.poolMaxIdle = poolMaxIdle;
}
public int getPoolMaxWait() {
return poolMaxWait;
}
public void setPoolMaxWait(int poolMaxWait) {
this.poolMaxWait = poolMaxWait;
}
}
获取JedisPool( redis.clients.jedis;)
@Service
public class RedisPoolFactory {
@Autowired
RedisConfig redisConfig;
@Bean // 将这个bean注入到/加载到 Spring容器里
public JedisPool jedisPoolFactory() {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
JedisPool jedisPool = new JedisPool(poolConfig,redisConfig.getHost(),
redisConfig.getPort(),redisConfig.getTimeout()*1000,
redisConfig.getPassword(),0);
return jedisPool;
}
}
@Autowired
JedisPool jedisPool;
Jedis jedis = jedisPool.getResource();
Jedis类就是对redis缓存操作的工具类了,剩下的就是封装调用,比较简单;