SpringBoot整合Redis集群

一、编辑properties文件

redis.clusters=192.168.126.174:7000,192.168.126.174:7001,192.168.126.174:7002,192.168.126.174:7003,192.168.126.174:7004,192.168.126.174:7005

二、编辑Redis的配置类

@Configuration
@PropertySource("classpath:/properties/redis.properties")
public class RedisConfig {
    /**
     * SpringBoot整合Redis集群
     */
    @Value("${redis.clusters}")
    private String jedisClusters;

    @Bean
    @Scope("prototype")
    public JedisCluster jedisCluster() {
        Set<HostAndPort> setNodes = new HashSet<>();
        String[] nodes = jedisClusters.split(",");
        for (String node : nodes) {
            String host = node.split(":")[0];
            Integer port = Integer.parseInt(node.split(":")[1]);
            HostAndPort hostAndPort = new HostAndPort(host, port);
            setNodes.add(hostAndPort);
        }
        return new JedisCluster(setNodes);
    }
}

 三、封装Mapper工具API

public class ObjectMapperUtil {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    public static String toJSON(Object obj) {
        String result = null;
        try {
            result = MAPPER.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;
    }

    public static <T> T toObj(String json, Class<T> targetClass) {
        T t = null;
        try {
            t=MAPPER.readValue(json,targetClass);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return t;
    }
}

四、自定义注解 

@Target(ElementType.METHOD)//注解对谁有效
@Retention(RetentionPolicy.RUNTIME)//运行时有效
public @interface CacheFind {
    String key() default "";//如果用户设定参数,则使用用户的,如果用户没有设定参数,就使用自动生成

    int seconds() default 0;
    //int seconds() default 0;//默认值为0
}

五、编辑CacheAOP

@Component  //将对象交给spring容器管理
@Aspect     //自定义切面
public class CacheAOP {

    @Autowired
    private JedisCluster jedis;

    @Around("@annotation(cacheFind)")
    public Object around(ProceedingJoinPoint joinPoint, CacheFind cacheFind) {
        //调用方法,获取key
        String key = getKey(joinPoint, cacheFind);
        String value = jedis.get(key);
        Object object = null;
        try {
            if (StringUtils.isEmpty(value)) {
                //缓存中没有数据,查询数据库
                object = joinPoint.proceed();
                String json = ObjectMapperUtil.toJSON(object);
                //判断是否需要超时设定
                if (cacheFind.seconds() > 0) {
                    jedis.setex(key, cacheFind.seconds(), json);
                } else {
                    //该数据永不超时
                    jedis.set(key, json);
                }
                System.out.println("AOP查询数据库!!!");
            } else {
                //需要动态的获取返回值类型
                MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
                Class<?> targetClass = methodSignature.getReturnType();
                object = ObjectMapperUtil.toObj(value, targetClass);
                System.out.println("AOP查询缓存!!!");
            }
        } catch (Throwable e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return object;
    }

    //动态获取key
    private String getKey(ProceedingJoinPoint joinPoint, CacheFind cacheFind) {
        //1.检查用户是否传递key
        String key = cacheFind.key();
        if (StringUtils.isEmpty(key)) {
            //包名.类名.方法名::第一个参数
            String className = joinPoint.getSignature().getDeclaringTypeName();
            String mothedName = joinPoint.getSignature().getName();
            Object arg0 = joinPoint.getArgs()[0];
            key = className + "." + mothedName + "::" + arg0;
        }
        return key;
    }
}

关于redis集群报错说明

上述报错信息表示没有可用的redis节点.排查步骤如下:

1.检查代码错误.   (CacheAOP类的jedis.close()注释掉)

2.检查Redis集群是否宕机.

3.  检查Linux系统的防火墙是否关闭关闭防火墙

4.  检查properties的配置文件中的IP地址是否正确

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值