《SpringBoot2从入门到工程实战》第十五篇:RedisCluster的接入

《SpringBoot2从入门到工程实战》第十五篇:RedisCluster的接入

在大型业务中,往往单实例的 Redis 很难满足QPS和存储空间的需求,所以在实际中,往往会部署 Redis Cluster 集群,SpringBoot 从 2.x 版本开始,对于 Redis Cluster 已经提供了非常成熟的支持。下面演示实际的使用。

本文使用 Jedis 作为底层的接入层,并没有使用 lettuce 是因为在 使用 lecttuce 时,发现有跟老的 Redis Cluster 集群存在不兼容的问题,巨坑。

本章示例工程名称:springboot_worker_rediscluster

代码地址:https://github.com/stamhe/SpringBoot-Work-Example

目录结构如下:

application.properties 配置内容:

# 如果没有密码,就留空
spring.redis.password=123456
# redis cluster 集群示例
spring.redis.cluster.nodes=192.168.1.100:6379,192.168.1.101:6379,192.168.1.102:6379,192.168.1.103:6379
spring.redis.timeout=500
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-idle=5
spring.redis.jedis.pool.min-idle=3
spring.redis.jedis.pool.max-wait=1000

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/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.stamhe.springboot</groupId>
    <artifactId>springboot_worker_rediscluster</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot_worker_rediscluster</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.70</version>
        </dependency>


    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

SpringbootWorkerRedisclusterApplication.java 主类内容:

package com.stamhe.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringbootWorkerRedisclusterApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(SpringbootWorkerRedisclusterApplication.class, args);
    }
    
}

RedisClusterConfig.java内容: (Jedis 版本)

package com.stamhe.springboot.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

// jedis
@Configuration
public class RedisClusterConfig {
    @Autowired
    private RedisConnectionFactory factory;
    
    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }
}

如果你想使用 lettuce 作为连接层,则 RedisClusterConfig.java 内容为:

@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisClusterConfig {
    @Bean
    public RedisTemplate<String, Object> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

HelloController类内容:

package com.stamhe.springboot.controller;

import com.alibaba.fastjson.JSON;
import com.stamhe.springboot.bean.UserBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;


@Controller
@RequestMapping("/hello")
public class HelloController {
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @RequestMapping("/hget")
    @ResponseBody
    public String hgetAction() {
        String hashKey = "userInfo";
    
        String userId = "166205";
        UserBean UserBean = (UserBean) redisTemplate.opsForHash().get(hashKey, userId);
        System.out.println(JSON.toJSONString(UserBean));
        
        return "success";
    }
    
    @RequestMapping("/hgetall")
    @ResponseBody
    public String hgetallAction() {
        String hashKey = "userInfo";
        Map<Object, Object> bookMap = redisTemplate.opsForHash().entries(hashKey);
        System.out.println("size " + bookMap.size());
        bookMap.entrySet().forEach(entry -> {
            String k = (String) entry.getKey();
            String v = (String) entry.getValue();
            UserBean UserBean = JSON.parseObject(v, UserBean.class);
            System.out.println(String.format("k = %s,v = %s", k, v));
        });
        
        return "success";
    }
}

UserBean.java内容:

package com.stamhe.springboot.bean;

import lombok.Data;

@Data
public class UserBean {
    private Long userId;
    private String name;
    private String address;
}

发表回复

您的电子邮箱地址不会被公开。

*

code

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据