SpringBoot中使用redis(单机+集群)

目录

引入依赖

参数配置

测试访问

RedisTemplate相关配置

集群版


Spring Boot中除了对常用的关系型数据库提供了优秀的自动化支持之外,对于很多NoSQL数据库一样提供了自动化配置的支持,包括:Redis, MongoDB, Elasticsearch, Solr和Cassandra。

Redis是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-Value数据库。

引入依赖

Spring Boot提供数据访问框架Spring Data Redis。可以通过引入spring-boot-starter-data-redis来配置依赖关系。


    org.springframework.boot
    spring-boot-starter-data-redis
    


    org.apache.commons
    commons-pool2

注:因为Springboot 2.0 中redis客户端默认使用了Lettue, 其依赖于commons,所以引入commons-pool2,否则程序启动会报错,无法实例化RedisTemplate。

参数配置

按照惯例在application.properties中加入Redis服务端的相关配置,具体说明如下:

## 是否启动日志SQL语句
spring.jpa.show-sql=true
# Redis 数据库索引(默认为 0)
spring.redis.database=0
spring.redis.host=192.168.3.26
spring.redis.port=6379
# Redis 服务器连接密码(默认为空)
spring.redis.password=
#连接超时
spring.redis.timeout=5000
# springboot 2.0 redis默认客户端已换成lettuce
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

测试访问

通过编写测试用例,举例说明如何访问Redis。

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class RedisControllerTest {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Test
    public void redisset() {//设置值
        redisTemplate.opsForValue().set("uuid", UUID.randomUUID().toString().replace("-",""));
    }

    @Test
    public void redisget() {//获取值
        String uuid = redisTemplate.opsForValue().get("uuid");
        log.info("获取UUID:{}", uuid);
    }

    @Test
    public void expire() {//失效时间设置为6秒
        redisTemplate.expire("uuid",6, TimeUnit.SECONDS);
    }
}

通过上面这段极为简单的测试案例演示了如何通过自动配置的StringRedisTemplate对象进行Redis的读写操作,该对象从命名中就可注意到支持的是String类型。如果有使用过spring-data-redis的开发者一定熟悉RedisTemplate接口,StringRedisTemplate就相当于RedisTemplate的实现。

除了String类型,实战中我们还经常会在Redis中存储对象,这时候我们就会想是否可以使用类似RedisTemplateObject>来初始化并进行操作。但是Spring Boot并不支持直接使用,需要我们自己实现RedisSerializer接口来对传入对象进行序列化和反序列化。

RedisTemplate相关配置

RedisTemplate相关配置类RedisConfig.java如下

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author swadian
 * @date 2022/3/2
 * @Version 1.0
 */
@Configuration
public class RedisConfig {

//    @Bean  会报错,不能存在多个RedisConnectionFactory 实例
//    LettuceConnectionFactory jedisConnectionFactory() {
//        return new LettuceConnectionFactory();
//    }

    /**
     * RedisTemplate相关配置
     * @param factory->配置来源LettuceConnectionConfiguration.class
     * @return
     * LettuceConnectionConfiguration.class 创建了连接工厂
     * @ConditionalOnClass({RedisClient.class}) 条件满足,实例化该Bean
     * this.createLettuceConnectionFactory(clientConfig);
     */
    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate template = new RedisTemplate<>();
        //1-配置连接工厂
        template.setConnectionFactory(factory);

        //2-使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)
        Jackson2JsonRedisSerializer jacksonSeial = new Jackson2JsonRedisSerializer(Object.class);

        ObjectMapper om = new ObjectMapper();
        //指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会跑出异常
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jacksonSeial.setObjectMapper(om);

        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        //值采用json序列化
        template.setValueSerializer(jacksonSeial);

        //设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jacksonSeial);
        return template;
    }
}

测试类如下:

import com.swadian.userdemo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RequestMapping("/redis")
@RestController
public class RedisController {

    private static int ExpireTime = 6;   // redis中存储的过期时间6s

    @Resource
    private RedisTemplate redisTemplate;

    @RequestMapping("set")
    public void redisset(String key, String value) {
        //直接传的对象
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
        User user = new User();
        user.setUserId(UUID.randomUUID().toString().replace("-", ""));
        user.setUserName("Mike");
        user.setUserAge(18);
        user.setUserSex("男");
        user.setCreateTime(simpleDateFormat.format(new Date()));
        user.setUpdateTime(simpleDateFormat.format(new Date()));
        redisTemplate.opsForValue().set("userDetails",user);
    }

    @PostMapping("get")
    public Object redisget(String key) {
        User user = (User) redisTemplate.opsForValue().get(key);
        return user;
    }

    @RequestMapping("expire")
    public boolean expire(String key) {
        return redisTemplate.expire(key, ExpireTime, TimeUnit.SECONDS);//秒
    }
}

集群版

集群版的使用很简单,就是在单机版的基础上,修改相关配置即可,将单机版的配置更改如下:

## 是否启动日志SQL语句
spring.jpa.show-sql=true
# Redis 数据库索引(默认为 0)
spring.redis.database=0
#spring.redis.host=192.168.3.26
#spring.redis.port=6379
# Redis 服务器连接密码(默认为空)
spring.redis.password=
#连接超时
spring.redis.timeout=5000
#集群配置
spring.redis.cluster.nodes=192.168.3.26:7001,192.168.3.26:7002,192.168.3.26:7003,192.168.3.26:7004,192.168.3.26:7005,192.168.3.26:7006
# springboot 2.0 redis默认客户端已换成lettuce
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

上边配置中主要是配置了spring.redis.cluster.nodes,去掉了单机节点。

以上便是Spring Boot中使用Redis的简单介绍,更多对于redis的操作使用,请参考Spring-data-redis Reference。

你可能感兴趣的:(redis,SpringBoot,redis,spring,boot,数据库,redis集群,缓存)