Redis学习之二 —— SpringBoot整合Redis单实例主从复制模式(Sentinel实现)—— 亲测可用

参考:https://blog.csdn.net/Mars13889146832/article/details/79534981

注意:这里是Redis单实例的,什么是单实例呢,就是只有一个主(master),后面会有多实例(多个master)的案例。

目录结构

redis.properties

redis.nodes=10.24.54.245:26379,10.24.54.246:26379,10.24.54.247:26379
redis.masterName=redisMaster
#redis.password=abc123456
redis.maxTotal=10000
redis.maxIdle=100
redis.minIdle=50
redis.timeout=30000

RedisConfig

package com.artisan.redis.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**  
 *    
 * @author zou yao 
 * @date 2018/3/12 下午6:25
 * Redis配置文件
 * 
 */ 
@Component
@PropertySource("classpath:conf/redis.properties")
@ConfigurationProperties(prefix = "redis")
public class RedisConfig {

    /**
     * 节点名称
     */
    private String nodes;

    /**
     * Redis服务名称
     */
    private String masterName;

    /**
     * 密码
     */
    private String password;

    /**
     * 最大连接数
     */
    private int maxTotal;

    /**
     * 最大空闲数
     */
    private int maxIdle;

    /**
     * 最小空闲数
     */
    private int minIdle;

    /**
     * 连接超时时间
     */
    private int timeout;

    

    public String getNodes() {
        return nodes;
    }

    public void setNodes(String nodes) {
        this.nodes = nodes;
    }

    public String getMasterName() {
        return masterName;
    }

    public void setMasterName(String masterName) {
        this.masterName = masterName;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getMaxTotal() {
        return maxTotal;
    }

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    public int getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public int getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(int minIdle) {
        this.minIdle = minIdle;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    @Override
    public String toString() {
        return "RedisConfig{" +
                "nodes='" + nodes + '\'' +
                ", masterName='" + masterName + '\'' +
                ", password='" + password + '\'' +
                ", maxTotal='" + maxTotal + '\'' +
                ", maxIdle='" + maxIdle + '\'' +
                ", minIdle='" + minIdle + '\'' +
                ", timeout='" + timeout + '\'' +
                '}';
    }
}

RedisInitConfig

package com.artisan.redis.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Set;

/**  
 *    
 * @author Fire Monkey 
 * @date 2018/3/12 下午6:28
 * redis初始化配置
 * 
 */ 
@Configuration
public class RedisInitConfig {

    /**
     * 日志打印对象
     */
    private Logger log = LoggerFactory.getLogger(RedisInitConfig.class);

    /**
     * 注入配置文件信息
     */
    @Autowired
    private RedisConfig redisConfig;

    
    /**  
     *    
     * @author Fire Monkey 
     * @date 2018/3/12 下午6:53
     * @return redis.clients.jedis.JedisPoolConfig
     * 初始化连接池配置对象
     *
     */ 
    @Bean(value = "jedisPoolConfig")
    public JedisPoolConfig initJedisPoolConfig(){
        log.info("JedisPool initialize start ...");
        JedisPoolConfig config = new JedisPoolConfig();

        //最大总量
        config.setMaxTotal(redisConfig.getMaxTotal());
        //设置最大空闲数量
        config.setMaxIdle(redisConfig.getMaxIdle());
        //设置最小空闲数量
        config.setMinIdle(redisConfig.getMinIdle());
        //常规配置
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        log.info("JedisPool initialize end ...");
        return config;
    }

    /**
     *
     * @author Fire Monkey
     * @date 下午7:20
     * @return redis.clients.jedis.JedisSentinelPool
     * 生成JedisSentinelPool并且放入Spring容器
     *
     */
    @Bean(value = "sentinelPool")
    public JedisSentinelPool initJedisPool(@Qualifier(value = "jedisPoolConfig") JedisPoolConfig jedisPoolConfig){

        Set<String>  nodeSet = new HashSet<>();
        //获取到节点信息
        String nodeString = redisConfig.getNodes();
        //判断字符串是否为空
        if(nodeString == null || "".equals(nodeString)){
            log.error("RedisSentinelConfiguration initialize error nodeString is null");
            throw new RuntimeException("RedisSentinelConfiguration initialize error nodeString is null");
        }
        String[] nodeArray = nodeString.split(",");
        //判断是否为空
        if(nodeArray == null || nodeArray.length == 0){
            log.error("RedisSentinelConfiguration initialize error nodeArray is null");
            throw new RuntimeException("RedisSentinelConfiguration initialize error nodeArray is null");
        }
        //循环注入至Set中
        for(String node : nodeArray){
            log.info("Read node : {}。" , node);
            nodeSet.add(node);
        }
        //创建连接池对象
        JedisSentinelPool jedisPool = new JedisSentinelPool(redisConfig.getMasterName() ,nodeSet ,
                jedisPoolConfig ,redisConfig.getTimeout() , redisConfig.getPassword());

        return jedisPool;

    }

    
}

RedisService

package com.artisan.redis.service;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.exceptions.JedisConnectionException;


/**  
 *    
 * @author Fire Monkey 
 * @date 2018/3/12 下午7:32
 * Reids工具通过Jedis实现与Redis交互
 * 
 */ 
@Component
public class RedisService {


    /**
     * 日志打印对象
     */
    private static Logger log = Logger.getLogger(RedisService.class);


    /**
     * Jedis对象池 所有Jedis对象均通过该池租赁获取
     */
    private static JedisSentinelPool sentinelPool;

    /**
     * 缓存数据成功
     */
    private final static String CACHE_INFO_SUCCESS = "OK";


    /**  
     *    
     * @author Fire Monkey 
     * @date 2018/3/12 下午7:34
     * 注入JedisSentinelPool
     *
     */ 
    @Autowired
    public  void setSentinelPool(JedisSentinelPool sentinelPool) {
        RedisService.sentinelPool = sentinelPool;
    }



    /**  
     *    
     * @author Fire Monkey 
     * @date 2018/3/12 下午7:35
     * @return redis.clients.jedis.Jedis
     * 获取到Jedis
     *
     */ 
    private static Jedis getJedis()  {
        Jedis jedis;
        try {
            jedis = sentinelPool.getResource();
            return  jedis;
        } catch (JedisConnectionException e) {
            log.error("获取Redis 异常", e);
            throw e;
        }
    }

    /**
     *
     * @author Fire Monkey
     * @date 2018/3/12 下午7:36
     * 缓存String类型的数据,数据不过期
     *
     */
    public static boolean setString(String key, String value) throws Exception {
        return setString(key, value, -1);
    }


    /**
     *
     * @author Fire Monkey
     * @date 2018/3/12 下午7:40
     * 缓存String类型的数据并设置超时时间
     *
     */
    public static boolean setString(String key, String value, int timeout) throws Exception {
        String result;
        Jedis jedis = null;
        try {
            jedis = getJedis();
            result = jedis.set(key, value);
            if (timeout != -1) {
                jedis.expire(key, timeout);
            }
            if (CACHE_INFO_SUCCESS.equals(result)) {
                return true;
            } else {
                return  false;
            }
        } finally {
            releaseRedis(jedis);
        }
    }

    /**
     *
     * @author Fire Monkey
     * @date 2018/3/12 下午7:46
     * 获取String类型的数据
     *
     */
    public static  String getString(String key) throws Exception {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            return jedis.get(key);
        } catch (Exception e) {
            throw e;
        } finally {
            releaseRedis(jedis);
        }
    }


    /**  
     *    
     * @author Fire Monkey 
     * @date 2018/3/12 下午7:49
     * @return void
     * 释放Jedis
     *
     */ 
    public static void releaseRedis(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }


    /**  
     *    
     * @author Fire Monkey 
     * @date 2018/3/12 下午7:55
     * @return boolean
     * 通过key删除缓存中数据
     *
     */ 
    public static boolean del(String key) throws Exception {
        Long num;
        Jedis jedis = null;
        Boolean result = false;
        try {
            jedis = getJedis();
            num = jedis.del(key);
            if (num.equals(1L)) {
                result = true;
            }
        }finally {
            releaseRedis(jedis);
        }
        return result;
    }
    
}

RedisController

package com.artisan.controller;

import com.artisan.redis.service.RedisService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/redis")
public class RedisController {

    @RequestMapping(value = "/setString/{key}/{value}")
    public ModelAndView index(ModelAndView modelAndView,
                              @PathVariable String key, @PathVariable String value) throws Exception {
        modelAndView.setViewName("index");

        List<String> userList=new ArrayList<String>();
        userList.add("admin");
        userList.add("user1");
        userList.add("user2");

        modelAndView.addObject("key", key);
        modelAndView.addObject("value", value);
        RedisService.setString(key, value);
        return modelAndView;
    }
}

别人的GitHub地址

  github传送门:git@github.com:MarsMuse/ArtisanCloud.git

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值