springboot接入cachecloud redis示例实践

最近项目中需要接入  Redis CacheCloud,   CacheCloud是一个开源的 Redis 运维监控云平台,功能十分强大,支持Redis 实例自动部署、扩容、碎片管理、统计、监控等功能, 特别是支持单机、sentinel 、cluster三种模式的自动部署,搭建redis集群一步到位轻松搞定。

java项目中 接入 CacheCloud redis的方式主要有两种。

第一种就是在 CacheCloud 上创建好redis实例后将对应的IP,端口直接配置以配置形式应用到项目中,优点是通用性好,原有项目改造成本低,不过万一后期CacheCloud上对redis进行管理扩容,那只能手动把每个项目的redis配置都改一遍了。

第二种CacheCloud 上创建好实例后有一个对应的appId,程序调用CacheCloud 平台的rest接口通过 appId获取redis相关配置,将程序中的redis配置  统一交给CacheCloud平台去管理维护,后期管理和扩容及其方便,不过程序改造成本比较高。

现在采用第二种方式接入,工程采用springboot,redis采用哨兵模式,redis客户端主要用spring-data-redis和redisson,    接入流程如下:

添加配置到pom.xml文件

  <!--cachecloud 相关jar包-->
    <dependency>
      <groupId>com.sohu.tv</groupId>
      <artifactId>cachecloud-open-client-redis</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>com.sohu.tv</groupId>
      <artifactId>cachecloud-open-client-basic</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>

    <dependency>
      <groupId>com.sohu.tv</groupId>
      <artifactId>cachecloud-open-common</artifactId>
      <version>1.0-SNAPSHOT</version>
    </dependency>

  <!--spring redis 和 redisson-->
     <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-redis</artifactId>
      <exclusions>
        <exclusion>
          <artifactId>jedis</artifactId>
          <groupId>redis.clients</groupId>
        </exclusion>
      </exclusions>
    </dependency>
    <dependency>
      <groupId>org.redisson</groupId>
      <artifactId>redisson</artifactId>
      <version>3.9.0</version>
    </dependency>

准备配置文件  cacheCloudClient.properties,启动项目时  VM参数追加 -Dcachecloud.config= 配置文件路径

http_conn_timeout = 3000
http_socket_timeout = 5000
client_version = 1.0-SNAPSHOT
domain_url = http://192.168.33.221:8585  #cachecloud实际路径
redis_cluster_suffix = /cache/client/redis/cluster/%s.json?clientVersion=
redis_sentinel_suffix = /cache/client/redis/sentinel/%s.json?clientVersion=
redis_standalone_suffix = /cache/client/redis/standalone/%s.json?clientVersion=
cachecloud_report_url = /cachecloud/client/reportData.json

基本思路是先通过cachecloud的restapi接口获取并解析redis节点的配置信息,然后就可以按照传统的访问redis的方式进行初始化,获取RedisTemplate对象。

java代码如下:

import com.alibaba.fastjson.JSONObject;
import com.sohu.tv.cachecloud.client.basic.heartbeat.ClientStatusEnum;
import com.sohu.tv.cachecloud.client.basic.util.ConstUtils;
import com.sohu.tv.cachecloud.client.basic.util.HttpUtils;
import com.sohu.tv.cachecloud.client.jedis.stat.ClientDataCollectReportExecutor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component
public class RedisProperties {

  public static Logger logger = LoggerFactory.getLogger(RedisProperties.class);

  /**
   * 构建锁
   */
  private static final Lock LOCK = new ReentrantLock();

  @Value("${cacheCloud.appId}") //cahcecloud 开通redis实例 应用id
  private Integer appId;

  @Getter
  @Setter
  private String masterName;

  @Getter
  @Setter
  private Set<Pair<String, String>> sentinelSet = new HashSet<>();

  private Boolean clientStatIsOpen=true;

  @Getter
  @Setter
  private String password;

  private Boolean getConfigSuccess = false;

  @PostConstruct
  public void init() {

    while (true) {
      try {
        LOCK.tryLock(10, TimeUnit.MILLISECONDS);
        if (!getConfigSuccess) {
          /**
           * http请求返回的结果是空的;
           */
          String response = HttpUtils.doGet(String.format(ConstUtils.REDIS_SENTINEL_URL, appId));
          if (response == null || response.isEmpty()) {
            logger.warn("get response from remote server error, appId: {}, continue...", appId);
            continue;
          }

          /**
           * http请求返回的结果是无效的;
           */
          JSONObject jsonObject = null;
          try {
            jsonObject = JSONObject.parseObject(response);
          } catch (Exception e) {
            logger.error("heartbeat error, appId: {}. continue...", appId, e);
          }
          if (jsonObject == null) {
            logger.error("get sentinel info for appId: {} error. continue...", appId);
            continue;
          }
          int status = jsonObject.getIntValue("status");
          String message = jsonObject.getString("message");

          /** 检查客户端版本 **/
          if (status == ClientStatusEnum.ERROR.getStatus()) {
            throw new IllegalStateException(message);
          } else if (status == ClientStatusEnum.WARN.getStatus()) {
            logger.warn(message);
          } else {
            logger.info(message);
          }

          /**
           * 有效的请求:取出masterName和sentinels;
           */
          masterName = jsonObject.getString("masterName");
          String sentinels = jsonObject.getString("sentinels");
          for (String sentinelStr : sentinels.split(" ")) {
            String[] sentinelArr = sentinelStr.split(":");
            if (sentinelArr.length == 2) {
              sentinelSet.add(Pair.of(sentinelArr[0], sentinelArr[1]));
            }
          }

          //收集上报数据
          if (clientStatIsOpen) {
            ClientDataCollectReportExecutor.getInstance();
          }
          password = jsonObject.getString("password");
          getConfigSuccess = true;
          return;
        }
      } catch (Throwable e) {//容错
        logger.error("error in build, appId: {}", appId, e);
      } finally {
        LOCK.unlock();
      }
      try {
        TimeUnit.MILLISECONDS.sleep(200 + new Random().nextInt(1000));//活锁
      } catch (InterruptedException e) {
        logger.error(e.getMessage(), e);
      }
    }
  }
}
import com.shunwang.buss.dispatchPay.provider.config.PropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.ReadMode;
import org.redisson.config.SentinelServersConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
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.net.UnknownHostException;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

@Configuration
public class RedisConfig {

  /**
   * JedisPoolConfig 连接池
   */
  @Bean
  public JedisPoolConfig jedisPoolConfig(RedisProperties properties) {
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    // 最大空闲数
    jedisPoolConfig.setMaxIdle(20);
    // 连接池的最大数据库连接数
    jedisPoolConfig.setMaxTotal(20);
    // 最大建立连接等待时间
    jedisPoolConfig.setMaxWaitMillis(3000);
    return jedisPoolConfig;
  }

  /**
   * 配置redis的哨兵
   */
  @Bean
  public RedisSentinelConfiguration sentinelConfiguration(RedisProperties properties) {
    RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration();
    // 配置redis的哨兵sentinel
    Set<RedisNode> redisNodeSet = properties.getSentinelSet().stream()
        .map(pair -> new RedisNode(pair.getLeft(), Integer.parseInt(pair.getRight())))
        .collect(Collectors.toSet());
    redisSentinelConfiguration.setSentinels(redisNodeSet);
    redisSentinelConfiguration.setMaster(properties.getMasterName());
    return redisSentinelConfiguration;
  }

  /**
   * 配置工厂
   */
  @Bean
  public RedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig, RedisSentinelConfiguration sentinelConfig) {
    JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfig, jedisPoolConfig);
    return jedisConnectionFactory;
  }

  @Bean
  public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory)
      throws UnknownHostException {
    RedisTemplate template = new RedisTemplate();
    template.setConnectionFactory(redisConnectionFactory);
    FastJsonRedisSerializer<Object> fastJsonRedisSerializer = new FastJsonRedisSerializer<>(Object.class);
    // 设置值(value)的序列化采用FastJsonRedisSerializer。
    template.setValueSerializer(fastJsonRedisSerializer);
    template.setHashValueSerializer(fastJsonRedisSerializer);
    // 设置键(key)的序列化采用StringRedisSerializer。
    template.setKeySerializer(new StringRedisSerializer());
    template.setHashKeySerializer(new StringRedisSerializer());
    template.afterPropertiesSet();
    return template;
  }

  /**
   * Redisson 配置
   */
  @Bean
  public RedissonClient redissonClient(RedisProperties properties) {
    Config config = new Config();
    List<String> newNodes = properties.getSentinelSet().stream()
        .map(pa -> "redis://" + pa.getLeft() + ":" + pa.getRight()).collect(toList());
    SentinelServersConfig serverConfig = config.useSentinelServers()
        .addSentinelAddress(newNodes.toArray(new String[newNodes.size()]))
        .setMasterName(properties.getMasterName())
        .setReadMode(ReadMode.SLAVE);

    if (StringUtils.isNotBlank(properties.getPassword())){
      serverConfig.setPassword(properties.getPassword());
    }
    return Redisson.create(config);
  }
}

到这里我们已经在Spring中 生成了RedisTemplate 和  RedissonClient 对象,无论是基本数据结构操作  还是分布式锁  都已经轻松支持了,具体使用就不展开了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • springcloud config配置读取优先级过程详解

    情景描述 最近在修复Eureka的静态页面加载不出的缺陷时,最终发现是远程GIT仓库将静态资源访问方式配置给禁用了(spring.resources.add-mappings=false).虽然最后直接修改远程GIT仓库的此配置项给解决了(spring.resources.add-mappings=true),但是从中牵涉出的配置读取优先级我们必须好好的再回顾下 springcloud config读取仓库配置 通过config client模块来读取远程的仓库配置,只需要在boostrap.p

  • spring cloud如何修复zuul跨域配置异常的问题

    前言 本文主要给大家介绍一下在zuul进行跨域配置的时候出现异常该如何解决的方法,分享出来供大家参考学习,下面话不多说了,来一起看看详细的介绍吧. 异常 The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed 实例 Access-Control-Allow-Credentials:true Access-Control-Allow-Credentials:t

  • spring cloud实现前端跨域问题的解决方案

    当我们需要将spring boot以restful接口的方式对外提供服务的时候,如果此时架构是前后端分离的,那么就会涉及到跨域的问题,那怎么来解决跨域的问题了,下面就来探讨下这个问题. 解决方案一:在Controller上添加@CrossOrigin注解 使用方式如下: @CrossOrigin // 注解方式 @RestController public class HandlerScanController { @CrossOrigin(allowCredentials="true"

  • Spring Cloud OAuth2 实现用户认证及单点登录的示例代码

    OAuth 2 有四种授权模式,分别是授权码模式(authorization code).简化模式(implicit).密码模式(resource owner password credentials).客户端模式(client credentials),具体 OAuth2 是什么,可以参考这篇文章.(http://www.ruanyifeng.com/blog/2014/05/oauth_2_0.html) 本文我们将使用授权码模式和密码模式两种方式来实现用户认证和授权管理. OAuth2 其

  • Spring Cloud Feign接口返回流的实现

    服务提供者 @GetMapping("/{id}") public void queryJobInfoLogDetail(@PathVariable("id") Long id, HttpServletResponse response) { File file = new File("xxxxx"); InputStream fileInputStream = new FileInputStream(file); OutputStream ou

  • 创建网关项目(Spring Cloud Gateway)过程详解

    创建网关项目 加入网关后微服务的架构图 创建项目 POM文件 <properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR3</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springfram

  • spring Cloud微服务跨域实现步骤

    这篇文章主要介绍了spring Cloud微服务跨域实现步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 第一步:在gateway网关的配置文件中加上下面这些: ly: cors: allowedOrigins: - http://manage.leyou.com - http://xxx.xxx.com # 允许哪些网址就继续加,不要写 *,否则cookie就无法使用了 allowedCredentials: true # 代表携带cook

  • springboot接入cachecloud redis示例实践

    最近项目中需要接入  Redis CacheCloud,   CacheCloud是一个开源的 Redis 运维监控云平台,功能十分强大,支持Redis 实例自动部署.扩容.碎片管理.统计.监控等功能, 特别是支持单机.sentinel .cluster三种模式的自动部署,搭建redis集群一步到位轻松搞定. java项目中 接入 CacheCloud redis的方式主要有两种. 第一种就是在 CacheCloud 上创建好redis实例后将对应的IP,端口直接配置以配置形式应用到项目中,优点

  • Docker 部署 SpringBoot 项目整合 Redis 镜像做访问计数示例代码

    最终效果如下 大概就几个步骤 1.安装 Docker CE 2.运行 Redis 镜像 3.Java 环境准备 4.项目准备 5.编写 Dockerfile 6.发布项目 7.测试服务 环境准备 系统:Ubuntu 17.04 x64 Docker 17.12.0-ce IP:45.32.31.101 一.安装 Docker CE 国内不建议使用:"脚本进行安装",会下载安装很慢,使用步骤 1 安装,看下面的链接:常规安装方式 1.常规安装方式 Ubuntu 17.04 x64 安装

  • 基于Docker实现Redis主从+哨兵搭建的示例实践

    目录 1.拉取镜像 2. 编写主 从配置文件 2.1 创建/home/redis/redis_conf目录: 2.2 编写主配置文件 2.3 编写从配置文件 2.4  编写从配置文件 3 编写sentinel配置文件 3.1创建哨兵配置文件 3.2编写哨兵配置文件 4  启动主节点容器 4.1启动主节点容器 4.2 启动从节点容器 5 存在的问题: 6.分别启动每个  docker容器里面的哨兵 6.1进入主节点容器 6.2查看文件 6.3启动主哨兵服务 6.4 启动两个从哨兵服务 6.5进入主

  • SpringBoot中使用Redis作为全局锁示例过程

    目录 一.模拟没有锁情况下的资源竞争 二.使用redis加锁 微服务的项目中,一个服务我们启动多份,在不同的进程中.这些服务是无状态的,而由数据存储容器(mysql/redis/es)进行状态数据的持久化.这就会导致资源竞争,出现多线程的问题. 一.模拟没有锁情况下的资源竞争 public class CommonConsumerService { //库存个数 static int goodsCount = 900; //卖出个数 static int saleCount = 0; publi

  • SpringBoot中使用Redis Stream实现消息监听示例

    目录 Demo环境 仓库地址 POM依赖 配置监听消息类 监听俩个stream的实现 [问题补充]确认完消息删除消息 [问题补充]自动初始化stream的key和group问题-最新更新-2021年12月4日 Demo环境 JDK8 Maven3.6.3 springboot2.4.3 redis_version:6.2.1 仓库地址 https://gitee.com/hlovez/redismq.git. POM依赖 <?xml version="1.0" encoding=

  • SpringBoot整合SpringDataRedis的示例代码

      本文介绍下SpringBoot如何整合SpringDataRedis框架的,SpringDataRedis具体的内容在前面已经介绍过了,可自行参考. 1.创建项目添加依赖   创建SpringBoot项目,并添加如下依赖: <dependencies> <!-- springBoot 的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId

  • 详解Redis主从复制实践

    复制简介 Redis 作为一门非关系型数据库,其复制功能和关系型数据库(MySQL)来说,功能其实都是差不多,无外乎就是实现的原理不同.Redis 的复制功能也是相对于其他的内存性数据库(memcached)所具备特有的功能. Redis 复制功能主要的作用,是集群.分片功能实现的基础:同时也是 Redis 实现高可用的一种策略,例如解决单机并发问题.数据安全性等等问题. 服务介绍 在本文环境演示中,有一台主机,启动了两个 Redis 示例. 实现方式 Redis 复制实现方式分为下面三种方式:

  • SpringBoot如何监控Redis中某个Key的变化(自定义监听器)

    目录 SpringBoot 监控Redis中某个Key的变化 1.声明 2.基本理念 3.实现和创建监听 4.基本demo的其他配置 5.基本测试 6.小结一下 SpringBoot自定义监听器 原理 示例 SpringBoot 监控Redis中某个Key的变化 1.声明 当前内容主要为本人学习和基本测试,主要为监控redis中的某个key的变化(感觉网上的都不好,所以自己看Spring源码直接写一个监听器) 个人参考: Redis官方文档 Spring-data-Redis源码 2.基本理念

  • springboot使用nacos的示例详解

    1.pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/PO

  • springboot 整合canal实现示例解析

    目录 前言 环境准备 一.快速搭建canal服务 搭建步骤 1.服务器使用docker快速安装一个mysql并开启binlog日志 2.上传canal安装包并解压 3.进入到第二步解压后的文件目录,并修改配置文件 4.启动canal服务 二.与springboot整合 1.Java中使用canal 2.编写一个demo 3.与springboot整合 4.application.yml 配置文件 5.核心工具类 6.提供一个配置类,在程序启动后监听数据变化 7.启动类 前言 在Mysql到Ela

随机推荐