Springboot实例连接redis单机模式和集群模式(网页框架:Swagger2)

27 阅读1分钟

一.redis单机模式

  1. 创建配置文件pom.xml
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.18</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
    <version>3.0.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>jakarta.servlet</groupId>
    <artifactId>jakarta.servlet-api</artifactId>
    <version>6.0.0</version>
    <scope>provided</scope>
</dependency>
  • Swagger2框架不适用用spring-boot 3.x版本,只能降级为2.x.x版本
  1. RedisSwaggerDemon.java
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class RedisSwaggerDemon {
    public static void main(String[] args) {
        SpringApplication.run(RedisSwaggerDemon.class,args);
    }
}
  1. application.properties
server.port=自定义swagger2服务端口
spring.application.name=demo
spring.swagger2.enabled=true
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
spring.redis.database=redis的数据库
spring.data.redis.repositories.enabled=true 
spring.redis.host=虚拟机的ip地址
spring.redis.port=redis端口号
spring.redis.password=redis的密码
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0

4.OrderController.java

package com.example.demo.controller;
import com.example.demo.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
//import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
@RestController
@Slf4j
@Api(tags="订单接口")
public class OrderController {
    @Resource
    private OrderService orderService;
    @ApiOperation("新增订单接口")
    @RequestMapping(value="/order/add",method= RequestMethod.POST)
    public void addOrder()
    {
        orderService.addOrder();
    }
    @ApiOperation("根据keyId查询接口")
    @RequestMapping(value="/order/{keyId}",method= RequestMethod.GET)
    public String  getOrderById(@PathVariable Integer keyId)
    {
         return orderService.getOrderById(keyId);
    }
}

5.OrderService.java

package com.example.demo.service;
//import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.ThreadLocalRandom;

@Service
@Slf4j
public class OrderService {
    public static final String ORDER_KEY = "ord:";
    @Resource
      //private RedisTemplate  redisTemplate;
        private StringRedisTemplate stringRedisTemplate;
    public void addOrder()
    {
        int keyId = ThreadLocalRandom.current().nextInt(2000)+1;
        String serialNo = UUID.randomUUID().toString();
        String key =  ORDER_KEY + keyId;
        String value = "订单" + serialNo;
        stringRedisTemplate.opsForValue().set(key,value);
        log.info("key:{}",key);
        log.info("value:{},",value);
    }
    public String getOrderById(Integer keyId)
    {
       return stringRedisTemplate.opsForValue().get(ORDER_KEY + keyId);
    }
}
  1. SwaggerConfig.java
package com.example.demo.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
     @Value("${spring.swagger2.enabled}")
     private  Boolean enabled;

     @Bean
     public Docket createRestApi()
     {
         return new Docket(DocumentationType.SWAGGER_2)
                 .apiInfo(apiInfo())
                 .enable(enabled)
                 .select()
                 .apis(RequestHandlerSelectors.basePackage("com.example.demo"))
                 .paths(PathSelectors.any())
                 .build();
     }
     public ApiInfo  apiInfo()
     {
         return new ApiInfoBuilder()
                 .title("springboot利用swagger2构建api接口文档"+"\t"+ DateTimeFormatter.ofPattern("yyyy-MM-dd").format(LocalDateTime.now()))
                 .description("swagger2操控连接redis")
                 .version("1.0")
                 .termsOfServiceUrl("https://www.baidu.com")
                 .build();
     }
}

7.RedisConfig.java

package com.example.demo.config;
public class RedisConfig {
}

二.集群模式

  1. 修改配置文件application.properties
spring.redis.password=密码
spring.redis.cluster.max-redirects=3
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.min-idle=0
#支持集群拓扑动态感应刷新,自适应拓扑刷新是否使用所有可用的更新,默认关闭
spring.redis.lettuce.cluster.refresh.adaptive=true
spring.redis.lettuce.cluster.refresh.period=2000
spring.redis.cluster.nodes=集群的节点