java架构之路-(Redis专题)SpringBoot链接Redis超简单

  上次咱们搭建了Redis的主从架构,哨兵架构以及咱们的集群架构,可是咱们一直还未投入到实战中去,此次咱们用jedis和springboot两种方式来操做一下咱们的redishtml

主从架构java

  如何配置我上次已经讲过了,http://www.javashuo.com/article/p-ulodfahx-eo.html。咱们此次主要看如何用java来操做redis,先来复习一下上次的配置,准备三台服务器,安装redis,保证互通,两台改成slave,配置replicaof IP 端口,主从复制是经过rdb文件来复制的。大概就这么多,配置再也不多说了,咱们直接上代码。node

  jedisweb

  建立一个Maven项目,引入咱们的jedis依赖包redis

<!-- 加入jedis依赖 -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

这里我就不封装链接工具类啦,咱们直接看下测试代码吧spring

public static void main(String[] args) { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(20); jedisPoolConfig.setMaxIdle(10); jedisPoolConfig.setMinIdle(5); // timeout,这里既是链接超时又是读写超时,从Jedis 2.8开始有区分connectionTimeout和soTimeout的构造函数
    JedisPool jedisPool = new JedisPool(jedisPoolConfig, "127.0.0.1", 6379, 3000, null); Jedis jedis = null; try { //从redis链接池里拿出一个链接执行命令
        jedis = jedisPool.getResource(); System.out.println(jedis.set("xiaocai", "666")); System.out.println(jedis.get("xiaocai")); } catch (Exception e) { e.printStackTrace(); } finally { //注意这里不是关闭链接,在JedisPool模式下,Jedis会被归还给资源池。
        if (jedis != null) jedis.close(); } }

主从的链接很简单的,设置链接参数,直接链接就能够操做咱们的redis了,主从的链接,就是基本的连接。数据库

  springbootapache

  咱们再来看一下springboot怎么来链接吧,创建一个springboot项目,什么也不用设置,创建一个最简单的就能够的,首先仍是加入咱们的Maven驱动包springboot

<!-- 加入redis链接池-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

加入咱们的redis的配置信息,放置在application.yml文件下便可。服务器

spring: redis: database: 0 # Redis数据库索引(默认为0) host: 127.0.0.1 # Redis服务器地址 port: 6379 # Redis服务器链接端口 password: # Redis服务器链接密码(默认为空) timeout: 5000 # 链接超时时间(毫秒) jedis: pool: max-active: 8 # 链接池最大链接数(使用负值表示没有限制) max-wait: -1 # 链接池最大阻塞等待时间(使用负值表示没有限制) max-idle: 8 # 链接池中的最大空闲链接 min-idle: 0 # 链接池中的最小空闲链接

这个也就不存在什么工具类了,内部都已经封装好了,咱们直接来上测试类吧

package com.redisclient.master_slave; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.data.redis.core.StringRedisTemplate; @RestController public class RedisMasterSlave { @Autowired private StringRedisTemplate stringRedisTemplate; @GetMapping(value = "/") public String getIndex(){ stringRedisTemplate.opsForValue().set("xiaocai", "888"); System.out.println(stringRedisTemplate.opsForValue().get("xiaocai")); return "小菜技术"; } }

  相比咱们上面的jedis还要简单,直接自动装配一下咱们的StringRedisTemplate便可,剩下的就是咱们的redis操做了,五种数据的基本操做以下。

redisTemplate.opsForValue();//操做字符串 
redisTemplate.opsForHash();//操做hash
redisTemplate.opsForList();//操做list
redisTemplate.opsForSet();//操做set
redisTemplate.opsForZSet();//操做有序set

还有什么更多的操做不知道的,欢迎来个人公众号内问答,我会依依给你解释清楚的。

哨兵架构

  哨兵架构,是主从的升级版,master节点宕机后,能够主动选取咱们的master节点。

  咱们仍是分为jedis和springboot两种方式分别来尝试链接一下咱们的哨兵架构,搭建我就不说啦,上次博文已经说过了。http://www.javashuo.com/article/p-ulodfahx-eo.html  

  jedis

  仍是老规矩,引入依赖,剩下的咱们直接来写测试类吧。

package com.redisclient.sentinel; import redis.clients.jedis.*; import java.util.HashSet; import java.util.Set; public class JedisClientSentinel { public static void main(String[] args) { JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxTotal(20); jedisPoolConfig.setMaxIdle(10); jedisPoolConfig.setMinIdle(5); String masterName = "mymaster"; Set<String> sentinels = new HashSet<String>(); sentinels.add(new HostAndPort("47.105.97.79", 6380).toString()); sentinels.add(new HostAndPort("47.105.97.142", 6380).toString()); sentinels.add(new HostAndPort("118.190.147.181", 6380).toString()); //JedisSentinelPool其实本质跟JedisPool相似,都是与redis主节点创建的链接池 //JedisSentinelPool并非说与sentinel创建的链接池,而是经过sentinel发现redis主节点并与其创建链接
        JedisSentinelPool jedisPool = new JedisSentinelPool(masterName, sentinels, jedisPoolConfig, 5000, null); Jedis jedis = null; try { //从redis链接池里拿出一个链接执行命令
            jedis = jedisPool.getResource(); System.out.println(jedis.set("xiaocai888", "666888")); System.out.println(jedis.get("xiaocai888")); } catch (Exception e) { e.printStackTrace(); } finally { //注意这里不是关闭链接,在JedisPool模式下,Jedis会被归还给资源池。
            if (jedis != null) jedis.close(); } } }

  最简单的理解就是咱们创建了一个set链接池。当哨兵节点宕机一个的时候,会尝试链接其它节点,当master节点宕机时,会报错链接错误,稍后会自动恢复的。 ✨

  springboot

  咱们先来修改一下咱们yml配置文件

#哨兵模式 spring: redis: database: 0 # Redis数据库索引(默认为0) host: 120.27.27.4 # Redis服务器地址 port: 6379 # Redis服务器链接端口 password: # Redis服务器链接密码(默认为空) timeout: 5000 # 链接超时时间(毫秒) sentinel: master: mymaster #主服务器所在集群名称 nodes: 115.28.208.105:26379,47.105.92.89:26379,118.190.151.92:26379

  而咱们的测试类和主从是同样的配置就能够了,springboot主要改一下配置就能够了。

集群架构

  上次咱们说过了咱们的集群架构,就是不少个小主从集合在一块儿,内部有半数机制,建议设置大于3的奇数个主从服务。

   这从咱们来搭建三组一主一从服务,咱们先来看一下jedis的代码,咱们内部redis是将16384分为了三个片区,为了确保每一个片区都存入数据咱们采用了随机生成的key。

  jedis

package com.redisclient.cluster; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.*; import java.io.IOException; import java.util.HashSet; import java.util.Random; import java.util.Set; public class JedisClientCluster { public static void main(String[] args) throws IOException { GenericObjectPoolConfig config = new GenericObjectPoolConfig(); config.setMaxTotal(20); config.setMaxIdle(10); config.setMinIdle(5); //这里将全部主从节点所有放入
        Set<HostAndPort> jedisClusterNode = new HashSet<HostAndPort>(); jedisClusterNode.add(new HostAndPort("120.27.27.4", 6379)); jedisClusterNode.add(new HostAndPort("47.105.86.150", 6379)); jedisClusterNode.add(new HostAndPort("47.105.84.186", 6379)); jedisClusterNode.add(new HostAndPort("115.28.208.105", 6379)); jedisClusterNode.add(new HostAndPort("47.105.92.89", 6379)); jedisClusterNode.add(new HostAndPort("118.190.151.92", 6379)); JedisCluster jedisCluster = null; try { //connectionTimeout:指的是链接一个url的链接等待时间 //soTimeout:指的是链接上一个url,获取response的返回等待时间
            jedisCluster = new JedisCluster(jedisClusterNode, 6000, 5000, 10, "xiaocai", config); while (true) { try { jedisCluster.set(getRandomString(4), "value" + getRandomString(4)); Thread.sleep(5000); } catch (Exception e) { e.printStackTrace(); } } } catch (Exception e) { e.printStackTrace(); } finally { if (jedisCluster != null) jedisCluster.close(); } } //length用户要求产生字符串的长度
    public static String getRandomString(int length) { String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; Random random = new Random(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { int number = random.nextInt(62); sb.append(str.charAt(number)); } return sb.toString(); } }

  springboot

  仍是老规矩改一下配置类 

# 集群模式 spring: redis: database: 0 # Redis数据库索引(默认为0) host: 120.27.27.4 # Redis服务器地址 port: 6379 # Redis服务器链接端口 password: xiaocai # Redis服务器链接密码(默认为空) timeout: 5000 # 链接超时时间(毫秒) cluster: nodes: 115.28.208.105:6379,47.105.92.89:6379,118.190.151.92:6379

  说到这里咱们的三种模式的链接就所有写完了,这些使用仍是一个比一个简单的,咱们来看下内部的通信和选举机制吧。

选举机制

  当slave发现本身的master变为FAIL状态时,便尝试进行Failover,以期成为新的master。因为挂掉的master可能会有 多个slave,从而存在多个slave竞争成为master节点的过程, 其过程以下:

1.slave发现本身的master变为FAIL

2.将本身记录的集群currentEpoch加1,并广播FAILOVER_AUTH_REQUEST 信息

3.其余节点收到该信息,只有master响应,判断请求者的合法性,并发送FAILOVER_AUTH_ACK,对每个epoch只发 送一次ack

4.尝试failover的slave收集master返回的FAILOVER_AUTH_ACK

5.slave收到超过半数master的ack后变成新Master(这里解释了集群为何至少须要三个主节点,若是只有两个,当其 中一个挂了,只剩一个主节点是不能选举成功的)

6.广播Pong消息通知其余集群节点。从节点并非在主节点一进入 FAIL 状态就立刻尝试发起选举,而是有必定延迟,必定的延迟确保咱们等待FAIL状态在 集群中传播,slave若是当即尝试选举,其它masters或许还没有意识到FAIL状态,可能会拒绝投票

  最近公司有一些事情,就先说到这里吧,有时间给你们说一下redis来实现分布式锁的机制,还有一个炒鸡好用的redis分布式锁。

 

最进弄了一个公众号,小菜技术,欢迎你们的加入

原文出处:https://www.cnblogs.com/cxiaocai/p/11715874.html

相关文章
相关标签/搜索