您的位置:首页 > 数据库 > Redis

spring-boot中使用redis

2017-11-21 00:00 441 查看
maven配置:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>


properties文件中配置redis信息:

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
spring.redis.database=1
# Redis服务器地址
spring.redis.host=192.168.1.181
# Redis服务器连接端口
spring.redis.port=6379
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=0
# redis过期时间600s,10分钟
redis.expiration=600
#从连接池获取连接时是否检验链接有效性
redis.testOnBorrow=true


配置类:

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

/**
* spring-boot项目中redis配置
* Author: liyang
* Date: 2017-11-21 14:34:31
* Version: 1.0
* Desc: Redis Configuration
*/
@Configuration
public class RedisConfig {

@Value("${spring.redis.database}")
private int index;
@Value("${spring.redis.host}")
private String hostName;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.pool.max-active}")
private int maxTotal;
@Value("${spring.redis.pool.max-idle}")
private int maxIdle;
@Value("${spring.redis.pool.min-idle}")
private int minIdle;
@Value("${spring.redis.pool.max-wait}")
private long maxWaitMillis;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.testOnBorrow}")
private boolean testOnBorrow;

@Bean(name = "stringRedisTemplate")
public StringRedisTemplate stringRedisTemplate(
@Qualifier("redisConnectionFactory") RedisConnectionFactory cf
) {
StringRedisTemplate temple = new StringRedisTemplate();
temple.setConnectionFactory(cf);
return temple;
}

@Bean(name = "redisTemplate")
public RedisTemplate<String, Object> redisTemplate(
@Qualifier("redisConnectionFactory") RedisConnectionFactory cf) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(cf);
return template;
}

@Bean(name = "redisConnectionFactory")
public RedisConnectionFactory connectionFactory() {
return this.ConnectionFactory(
hostName,
password,
index,
port,
timeout,
maxIdle,
minIdle,
maxTotal,
maxWaitMillis,
testOnBorrow);
}

/**
* 构造RedisConnectionFactory
*
* @param hostName      host
* @param password      pwd
* @param index         db index
* @param port          端口
* @param timeout       连接超时时间
* @param maxIdle       max-Idle
* @param minIdle       min-Idle
* @param maxTotal      最大连接数
* @param maxWaitMillis 最大等待毫秒数
* @param testOnBorrow  test
* @return RedisConnectionFactory
*/
private RedisConnectionFactory ConnectionFactory(String hostName,
String password,
int index,
int port,
int timeout,
int maxIdle,
int minIdle,
int maxTotal,
long maxWaitMillis,
boolean testOnBorrow) {
JedisConnectionFactory jedis = new JedisConnectionFactory();
jedis.setHostName(hostName);
jedis.setPort(port);
jedis.setTimeout(timeout);
if (StringUtils.isNotEmpty(password)) {
jedis.setPassword(password);
}
if (index != 0) {
jedis.setDatabase(index);
}
jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, minIdle, testOnBorrow));
// 初始化连接pool
jedis.afterPropertiesSet();
RedisConnectionFactory factory = jedis;
return factory;
}

private static JedisPoolConfig poolCofig(int maxIdle,
int maxTotal,
long maxWaitMillis,
int minIdle,
boolean testOnBorrow) {
JedisPoolConfig poolCofig = new JedisPoolConfig();
poolCofig.setMaxIdle(maxIdle);
poolCofig.setMaxTotal(maxTotal);
poolCofig.setMaxWaitMillis(maxWaitMillis);
poolCofig.setMinIdle(minIdle);
poolCofig.setTestOnBorrow(testOnBorrow);
return poolCofig;
}
}


使用方式:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
* Created by 李阳 on 2017/3/16/016.
*/
@Controller
@RequestMapping("/redis")
public class RedisDemo {

@Autowired
private RedisTemplate redisTemplate;

@RequestMapping(value = "/test", method = RequestMethod.GET)
@ResponseBody
public void testRedis() {
redisTemplate.opsForValue().set("kevin", "lee");   //向redis中保存值,key=kevin,value=lee
System.out.println(redisTemplate.hasKey("kevin")); //查看redis中是否保存了key为kevin的值
}
}


下面为便于使用,定义的一个工具类:

import com.kevin.User;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Repository("redisDemo ")
public class RedisDemo {

private int cacheSeconds = 900000;

private ValueOperations<String, Object> valueOperations;

@Resource(name = "redisTemplateOfCache")
private RedisTemplate<String, Object> redisTemplate;

//@PostConstruct表示初始化bean之前进行的操作,同理,@PreDestroy表示销毁bean之前进行的操作
@PostConstruct
private void init() {
valueOperations = redisTemplate.opsForValue();
}

/**
* 保存对象
*/
public void save(User user) {
valueOperations.set(user.getUid(), user, cacheSeconds, TimeUnit.SECONDS);
}

/**
* 更新对象
*
* @param user 实例
*/
public void update(User user) {
valueOperations.set(user.getUid(), user, cacheSeconds, TimeUnit.SECONDS);
}

/**
* 根据id查询对象
*
* @param key 实例uuid
*/
public User findOne(String key) {
return (User) valueOperations.get(key);
}

/**
* 查询所有对象
*/
public List<Object> findAll() {
Set<String> strs = redisTemplate.keys("*");
return valueOperations.multiGet(strs);
}

/**
* 删除对象
*
* @param key 实例uids
*/
public void delete(String key) {
redisTemplate.delete(key);
}

/**
* 获取token的有效期
*
* @param key
*/
public long getExpireTime(String key) {
long time = redisTemplate.getExpire(key);
return time;
}

/**
* 获取token的有效期---秒
*
* @param key
* @return
*/
public long getExpireTimeType(String key) {
long time = redisTemplate.getExpire(key, TimeUnit.SECONDS);
return time;
}

/**
* 获取token的有效期---分
*
* @return
*/
public long getExpireTimeTypeForMin(String key) {
long time = redisTemplate.getExpire(key, TimeUnit.MINUTES);
return time;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring-boot redis