我是靠谱客的博主 酷酷蜻蜓,最近开发中收集的这篇文章主要介绍spring-boot2.x 中使用redis,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

2019独角兽企业重金招聘Python工程师标准>>> 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配置:

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

 

properties文件中配置redis信息:

# REDIS (RedisProperties)
# Redis数据库索引(默认为0)
token.redis.database=1
user.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过期时间600s10分钟
redis.expiration=600
#从连接池获取连接时是否检验链接有效性
redis.testOnBorrow=true

 

基础类RedisBaseRepository<T>

private ValueOperations<String, T> valueOperations;
    private StringRedisTemplate stringRedisTemplate;
    private RedisTemplate<String, T> redisTemplate;

    public RedisBaseRepository(StringRedisTemplate stringRedisTemplate, RedisTemplate<String, T> 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<T> 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, 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<String, Object> redisTemplate() {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(redisConnectionFactory(tokenIndex));
        return template;
    }

    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(redisConnectionFactory(tokenIndex));
        return temple;
    }

    @Bean
    public RedisTemplate<String, User> userRedisTemplate() {
        RedisTemplate<String, User> template = new RedisTemplate<String, User>();
        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<Object> {
        @Autowired
        public TokenRedisRepository(StringRedisTemplate stringRedisTemplate, RedisTemplate<String, Object> redisTemplate) {
            super(stringRedisTemplate, redisTemplate);
        }
    }

    @Component
    public class UserRedisRepository extends RedisBaseRepository<User> {
        @Autowired
        public UserRedisRepository(StringRedisTemplate userStringRedisTemplate, RedisTemplate<String, User> 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

最后

以上就是酷酷蜻蜓为你收集整理的spring-boot2.x 中使用redis的全部内容,希望文章能够帮你解决spring-boot2.x 中使用redis所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(39)

评论列表共有 0 条评论

立即
投稿
返回
顶部