栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Springboot整合redis(单机+哨兵)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Springboot整合redis(单机+哨兵)

Springboot整合redis(单机+哨兵)

介绍:配置文件中可根据是否配置了哨兵模式,如果配置了则按照哨兵模式运行,如果没有配置哨兵模式,则按照单机模式运行。

一、引入依赖
        
            org.springframework.boot
            spring-boot-starter-data-redis
            
                
                    redis.clients
                    jedis
                
                
                    io.lettuce
                    lettuce-core
                
            
        
        
            redis.clients
            jedis
            ${redis.version}
        
二、配置文件
spring:
  redis:
    host: 192.168.3.113 #单机模式,哨兵模式可不配置
    port: 6379 #单机模式,哨兵模式可不配置
    password: 123456
    timeout: 10000
    database: 0
    lettuce:
      pool:
        max-active: 180 #连接池最大连接数(使用负值表示没有限制)
        max-idle: 10 #连接池中的最大空闲连接
        max-wait: 1500 #连接池最大阻塞等待时间(使用负值表示没有限制)
    sentinel: #哨兵模式,单机模式不要配置
      master: mymaster #哨兵模式,单机模式不要配置
      nodes: 192.168.3.201:26379,192.168.3.202:26379,192.168.3.203:26379 #哨兵模式,单机模式不要配置
三、配置类
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.time.Duration;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
@EnableAutoConfiguration
public class RedisConfig {

    @Value("${spring.redis.host:}")
    private String host;

    @Value("${spring.redis.port:6379}")
    private int port;

    @Value("${spring.redis.timeout:10000}")
    private int timeout;

    @Value("${spring.redis.lettuce.pool.max-idle:10}")
    private int maxIdle;

    @Value("${spring.redis.lettuce.pool.max-wait:1500}")
    private long maxWaitMillis;

    @Value("${spring.redis.lettuce.pool.max-active:180}")
    private int maxActive;

    @Value("${spring.redis.password:}")
    private String password;

    @Value("${spring.redis.database:}")
    private String database;

    @Value("${spring.redis.sentinel.nodes:}")
    private String nodes;

    @Value("${spring.redis.sentinel.master:}")
    private String master;


    @Bean
    @ConfigurationProperties(prefix="spring.redis")
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setMaxTotal(maxActive);
        return config;
    }

//    @Bean
//    public RedisSentinelConfiguration sentinelConfiguration(){
//        RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
//        //配置matser的名称
//        redisSentinelConfiguration.master(master);
//        //配置redis的哨兵sentinel
//        Set redisNodeSet = new HashSet<>();
//        if (StringUtils.isNotBlank(master) && StringUtils.isNotBlank(nodes)) {
//            String[] nodeSplit = nodes.split(",");
//            List nodeList = Arrays.asList(nodeSplit);
//            nodeList.forEach(x->{
//                redisNodeSet.add(new RedisNode(x.split(":")[0],Integer.parseInt(x.split(":")[1])));
//            });
//        }
//        redisSentinelConfiguration.setSentinels(redisNodeSet);
        redisSentinelConfiguration.setSentinelPassword(password);
//        return redisSentinelConfiguration;
//    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        JedisConnectionFactory jedisConnectionFactory = null;
        //判断redis是单机模式还是哨兵模式
        if (StringUtils.isBlank(master) || StringUtils.isBlank(nodes)) {
            RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
            redisStandaloneConfiguration.setHostName(host);
            redisStandaloneConfiguration.setPassword(password);
            redisStandaloneConfiguration.setDatabase(Integer.parseInt(database));
            redisStandaloneConfiguration.setPort(port);
            JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();
            jedisClientConfiguration.connectTimeout(Duration.ofMillis(timeout));
            JedisClientConfiguration jedisClientConfigurationNew = jedisClientConfiguration.usePooling().poolConfig(jedisPoolConfig).build();
            jedisConnectionFactory = new JedisConnectionFactory(redisStandaloneConfiguration,jedisClientConfigurationNew);
        } else {
            RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
            //配置matser的名称
            redisSentinelConfiguration.master(master);
            //配置redis的哨兵sentinel
            Set redisNodeSet = new HashSet<>();
            if (StringUtils.isNotBlank(nodes)) {
                String[] nodeSplit = nodes.split(",");
                List nodeList = Arrays.asList(nodeSplit);
                nodeList.forEach(x->{
                    redisNodeSet.add(new RedisNode(x.split(":")[0],Integer.parseInt(x.split(":")[1])));
                });
            }
            redisSentinelConfiguration.setSentinels(redisNodeSet);
            redisSentinelConfiguration.setPassword(password);
            jedisConnectionFactory = new JedisConnectionFactory(redisSentinelConfiguration,jedisPoolConfig);
        }
        return jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate redisTemplate(JedisConnectionFactory jedisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(jedisConnectionFactory);
        return redisTemplate;
    }

}

四、Redis调用方法Service

新增一个IRedisService接口

import java.util.List;
import java.util.Map;
import java.util.Set;

public interface IRedisService {

    
    String get(String key);

    
    boolean set(String key, Object value);

    
    Object hget(String hkey, String key);


    
    boolean expire(String key, int second);

    
    void del(String... key);

    
    public long getExpire(String key);

    
    public boolean hasKey(String key);

    
    public boolean set(String key, Object value, long time);

    
    public long incr(String key, long delta);

    
    public long decr(String key, long delta);

    
    public Map hmget(String key);

    
    public boolean hmset(String key, Map map);

    
    public boolean hmset(String key, Map map, long time);

    
    public boolean hset(String key, String item, Object value);

    
    public boolean hset(String key, String item, Object value, long time);

    
    public void hdel(String key, Object... item);

    
    public boolean hHasKey(String key, String item);

    
    public double hincr(String key, String item, double by);

    
    public double hdecr(String key, String item, double by);

    
    public Set sGet(String key);
    
    public boolean sHasKey(String key, Object value);
    
    public long sSet(String key, Object... values);
    
    public long sSetAndTime(String key, long time, Object... values);
    
    public long sGetSetSize(String key);
    
    public long setRemove(String key, Object... values);
    // ===============================list=================================
    
    public List lGet(String key, long start, long end);
    
    public long lGetListSize(String key);
    
    public Object lGetIndex(String key, long index);
    
    public boolean lSet(String key, Object value);
    
    public boolean lSet(String key, Object value, long time);
    
    public boolean lSet(String key, List value);
    
    public boolean lSet(String key, List value, long time);
    
    public boolean lUpdateIndex(String key, long index, Object value);
    
    public long lRemove(String key, long count, Object value);

}

 

接口实现类:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.dc.service.IDCRedisService;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service("jedisService")
public class RedisService implements IRedisService {

    @Autowired
    private RedisTemplate redisTemplate;


    
    @Override
    public String get(String key) {
        if (key != null) {
            if (redisTemplate.opsForValue().get(key) != null) {
                return redisTemplate.opsForValue().get(key).toString();
            }

        }
        return null;
    }

    
    @Override
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @Override
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
    @Override
    public boolean expire(String key, int second) {
        try {
            if (second > 0) {
                redisTemplate.expire(key, second, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @Override
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    
    @Override
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    
    @Override
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @Override
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @Override
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    
    @Override
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // ================================Map=================================

    
    @Override
    public Map hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    
    @Override
    public boolean hmset(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @Override
    public boolean hmset(String key, Map map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, (int) time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @Override
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @Override
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key,(int) time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    
    @Override
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    
    @Override
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    
    @Override
    public double hincr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }

    
    @Override
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }

    // ============================set=============================
    
    @Override
    public Set sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public long sSet(String key, Object... values) {
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    @Override
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, (int) time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    @Override
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    @Override
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    // ===============================list=================================
    
    @Override
    public List lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    
    @Override
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    @Override
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0){
                expire(key, (int) time);
            }

            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean lSet(String key, List value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean lSet(String key, List value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, (int) time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    
    @Override
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

}



转载请注明:文章转载自 www.mshxw.com
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号