-----------------------------------------------------------------1
类1:JedisClientSingle:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
@Component
public class JedisClientSingle {
@Autowired
private JedisPool jedisPool;
//获取key的value值
public String get(String key) {
Jedis jedis = jedisPool.getResource();
String str = "";
try {
str = jedis.get(key);
} finally {
try {
jedis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return str;
}
public String set(String key, String value) {
Jedis jedis = jedisPool.getResource();
String str = "";
try {
str = jedis.set(key, value);
} finally {
try {
jedis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return str;
}
public String setex(String key, int seconds, String value) {
Jedis jedis = jedisPool.getResource();
String str = "";
try {
str = jedis.setex(key, seconds, value);
} finally {
try {
jedis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return str;
}
}
--------------------------------------------------------------2
类2:RedisCacheConfiguration:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Configuration
@EnableCaching
public class RedisCacheConfiguration extends CachingConfigurerSupport {
Logger logger = LoggerFactory.getLogger(RedisCacheConfiguration.class);
@Value("${redis.master.host}")
private String redisHost;
@Value("${redis.master.port}")
private String redisPort;
@Value("${redis.master.password}")
private String redisPassword;
private int timeout = 0;
private int maxIdle = 20; //最大等待连接中的数量
private long maxWaitMillis = 5000; //最大建立连接等待时间
@Bean
public JedisPool redisPoolFactory() {
logger.info("JedisPool注入成功!!");
logger.info("redis地址:" + redisHost + ":" + redisPort);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
jedisPoolConfig.setMaxIdle(maxIdle);
jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
JedisPool jedisPool = new JedisPool(jedisPoolConfig, redisHost, Integer.parseInt(redisPort), timeout, redisPassword);
return jedisPool;
}
}
-------------------------------------------------------------3
使用:
jedisClientSingle.setex(userInfo.getUserName(), 1800, subject.getSession().getId().toString());
完!