博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
spring-boot2.x 中使用redis
阅读量:7091 次
发布时间:2019-06-28

本文共 8588 字,大约阅读时间需要 28 分钟。

hot3.png

新项目升级到spring-boot2时,发现某些原有用法已过时,不推荐使用,所以今天主要是解决过时问题,同时演示配置多个redis的用法。如下:

过时方法:

JedisConnectionFactory 类下:
public void setHostName(String hostName)
public void setPassword(String password)
public void setPort(int port)
public void setTimeout(int timeout)
public void setPoolConfig(JedisPoolConfig poolConfig)
public void setDatabase(int index)

maven配置:

org.springframework.boot
spring-boot-starter-data-redis

 

properties文件中配置redis信息:

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

 

基础类RedisBaseRepository<T>

private ValueOperations
valueOperations; private StringRedisTemplate stringRedisTemplate; private RedisTemplate
redisTemplate; public RedisBaseRepository(StringRedisTemplate stringRedisTemplate, RedisTemplate
redisTemplate) { this.valueOperations = redisTemplate.opsForValue(); this.redisTemplate = redisTemplate; this.stringRedisTemplate = stringRedisTemplate; } /** * 缓存字符串 * * @param key * @param value */ public void saveString(String key, String value, Integer cacheTime, TimeUnit timeUnit) { stringRedisTemplate.opsForValue().set(key, value, cacheTime, timeUnit); } /** * 获得字符串 * * @param key */ public String getString(String key) { return stringRedisTemplate.opsForValue().get(key); } /** * 更新字符串 * * @param key */ public String updateString(String key, String value) { return stringRedisTemplate.opsForValue().getAndSet(key, value); } /** * 删除字符串 * * @param key */ public void deleteString(String key) { stringRedisTemplate.delete(key); } /** * 保存对象 */ public void save(String key, T value, Integer cacheTime, TimeUnit timeUnit) { valueOperations.set(key, value, cacheTime, timeUnit); } /** * 更新对象 * * @param value 实例 */ public void update(String key, T value, Integer cacheTime, TimeUnit timeUnit) { valueOperations.set(key, value, cacheTime, timeUnit); } /** * 根据id查询对象 * * @param key 实例uuid */ public T findOne(String key) { T obj = valueOperations.get(key); return obj; } /** * 查询所有对象 */ public List
findAll() { Set
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, TimeUnit timeUnit) { long time = redisTemplate.getExpire(key, timeUnit); return time; }

 

配置类@Configuration MultipleRedisConfiguration

@Value("${token.redis.database}")    private int tokenIndex;    @Value("${user.redis.database}")    private int userIndex;    @Value("${redis.host}")    private String hostName;    @Value("${redis.password}")    private String password;    @Value("${redis.port}")    private int port;    @Value("${redis.pool.max-active}")    private int maxTotal;    @Value("${redis.pool.max-idle}")    private int maxIdle;    @Value("${redis.pool.min-idle}")    private int minIdle;    @Value("${redis.pool.max-wait}")    private long maxWaitMillis;    @Value("${redis.timeout}")    private int timeout;    @Value("${redis.testOnBorrow}")    private boolean testOnBorrow;    @Bean    public RedisTemplate
redisTemplate() { RedisTemplate
template = new RedisTemplate
(); template.setConnectionFactory(redisConnectionFactory(tokenIndex)); return template; } @Bean public StringRedisTemplate stringRedisTemplate() { StringRedisTemplate temple = new StringRedisTemplate(); temple.setConnectionFactory(redisConnectionFactory(tokenIndex)); return temple; } @Bean public RedisTemplate
userRedisTemplate() { RedisTemplate
template = new RedisTemplate
(); template.setConnectionFactory(redisConnectionFactory(userIndex)); return template; } @Bean public StringRedisTemplate userStringRedisTemplate() { StringRedisTemplate temple = new StringRedisTemplate(); temple.setConnectionFactory(redisConnectionFactory(userIndex)); return temple; } @Component public class TokenRedisRepository extends RedisBaseRepository
{ @Autowired public TokenRedisRepository(StringRedisTemplate stringRedisTemplate, RedisTemplate
redisTemplate) { super(stringRedisTemplate, redisTemplate); } } @Component public class UserRedisRepository extends RedisBaseRepository
{ @Autowired public UserRedisRepository(StringRedisTemplate userStringRedisTemplate, RedisTemplate
userRedisTemplate) { super(userStringRedisTemplate, userRedisTemplate); } } /* * redisConnectionFactory * @description:构造RedisConnectionFactory * @author 李阳 * @date 2018/12/27 * @params [index] * @return org.springframework.data.redis.connection.RedisConnectionFactory */ public RedisConnectionFactory redisConnectionFactory(int index) { RedisStandaloneConfiguration con = new RedisStandaloneConfiguration(); con.setHostName(hostName); con.setPort(port); if (StringUtils.isNotEmpty(password)) { con.setPassword(RedisPassword.of(password)); } if (index != 0) { con.setDatabase(index); } JedisClientConfiguration clientConfig = ((JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder() .connectTimeout(Duration.ofMillis(timeout)).readTimeout(Duration.ofMillis(timeout))) .poolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, minIdle, testOnBorrow)).build(); JedisConnectionFactory jedis = new JedisConnectionFactory(con, clientConfig); jedis.afterPropertiesSet(); return jedis; } /* * poolCofig * @description:构造连接池配置 * @author 李阳 * @date 2018/12/27 * @params [maxIdle, maxTotal, maxWaitMillis, minIdle, testOnBorrow] * @return redis.clients.jedis.JedisPoolConfig */ 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; }

 

 

使用方式:

@Autowired    private MultipleRedisConfiguration.TokenRedisRepository tokenRedisRepository;    @Autowired    private MultipleRedisConfiguration.UserRedisRepository userRedisRepository;    /*     * getLatestIMToken      * @description:获得redis中存储的token     * @author 李阳     * @date 2018/11/29     * @params []     * @return java.lang.String     */    public String getLatestIMToken() {        //redis中token        String token = tokenRedisRepository.getString("token");        //token有效期小于等于一天或为空时,更新token        if (StringUtils.isBlank(token) || 1 >= tokenRedisRepository.getExpireTimeType("token", TimeUnit.DAYS)) {            token = "Bearer 11111111111111111111";            //更新或保存token 55天            tokenRedisRepository.saveString("token", token, 55, TimeUnit.DAYS);            return token;        }        return token;    }    /*     * getUser     * @description:获得redis中的user对象     * @author 李阳     * @date 2018/12/27     * @params []     * @return User     */    public User getUser() {        //redis中user        User user = userRedisRepository.findOne("user");        //user有效期小于等于半小时或为空时,更新user        if (null == user || 30 >= userRedisRepository.getExpireTimeType("user", TimeUnit.MINUTES)) {            user = new User("name", "mobile");            //更新或保存user 3小时            userRedisRepository.save("user", user, 3, TimeUnit.HOURS);            return user;        }        return user;    }

转载于:https://my.oschina.net/kevin2kelly/blog/2994073

你可能感兴趣的文章
对libevent+多线程服务器模型的C++封装类
查看>>
iOS本地数据保存
查看>>
windows下mysql忘记root密码的解决办法
查看>>
[蛋疼]猜测下一波浮点数指数位与小数位的分配
查看>>
cgic程序的编写遇到的问题
查看>>
haproxy url load balancing (url 负载均衡)
查看>>
Radix Tree in Linux Kernel
查看>>
PHP常见错误收集
查看>>
一对多的两个表,查询主表的信息和主表在子表中的记录条数
查看>>
从程序员入门到“第一个项目”的一些事
查看>>
转-Pentaho技术白皮书中文版(三)--构建新组件
查看>>
SpringSrcureCode在grails中实现用户--角色--权限的管理
查看>>
java Servlet 下载 itext 生成的2003 word 文档(java生成word文档3)
查看>>
Delphi 查找标题已知的窗口句柄,遍历窗口控件句柄(转)
查看>>
单例模式
查看>>
最锋利的jQuery源码、电子书及视频教程合集(共46个)
查看>>
JavaScript 内置对象!
查看>>
解决ubuntu下打不开rar文件
查看>>
内核启动过程
查看>>
在使用ibatis实现多条件模糊查询的语句
查看>>