Spring Boot 配置Redis数据库

  上一章我在docker中配置redis数据库,接下来就开始在spring boot框架中区去继承redis,并使用redis存储数据的演示

  导入jar包

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>2.3.0.RELEASE</version>
</dependency>

  在.properties文件中配置reids,其中没有被注释的是常用的(手动翻译,有错请提出,小编会改正的)

# redis配置
# 是否开启redis缓存  true开启   false关闭
spring.redis.open=true
# Redis数据库索引(默认为0)
spring.redis.database=0
# 连接url
# spring.redis.url=
# redis服务器地址
spring.redis.host=127.0.0.1
# redis服务器密码
spring.redis.password=password
# redis服务器端口
spring.redis.port=6379
# 是否启用SSL连接
spring.redis.ssl=false
# 连接超时时长(毫秒)
spring.redis.timeout=6000ms
# 客户端名称
# spring.redis.client-name=
# redis服务器的名字
# spring.redis.sentinel.master=
# 主机端口列表
# spring.redis.sentinel.nodes=
# 要启动的主机端口列表
# spring.redis.cluster.nodes=
# 执行命令时要遵循的最大重定向数
# spring.redis.cluster.max-redirects=10
# 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=10
# 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=5
# 连接池最大连接数(使用负值表示没限制)
spring.redis.jedis.pool.max-active=10
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
# 两个空闲连接的线程时间
# spring.redis.jedis.pool.time-between-eviction-runs=
# 关闭超时时间
# spring.redis.lettuce.shutdown-timeout=100

  完成上面的配置后,现在开始简单的测试,通过去查询mysql数据库,然后将数据存在redis中,首先创建实体类并实现序列化接口

@Data
@ApiModel(value = "用户表")
@TableName(value = "user")//表格注解,指定数据库表格
public class User implements Serializable {//实现序列化接口,保证能存入redis
    @ApiModelProperty(value = "主键id")
    @TableId(value = "id", type = IdType.AUTO)//主键注解,指定主键
    private Integer id;
    @ApiModelProperty(value = "姓名")
    @TableField(value = "name")//字段注解,指定字段
    private String name;
    @ApiModelProperty(value = "年龄")
    @TableField(value = "age")
    private Integer age;
    @ApiModelProperty(value = "邮箱")
    @TableField(value = "email")
    private String email;
}

  使用默认的redis配置实现redis功能测试

import com.dyh.peachsys.service.IUserService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class PeachsysApplicationTests {
    /**
     * redis模板对象
     * 封装了基本的方法
     */
    @Autowired
    private RedisTemplate redisTemplate;
    @Test
    void contextLoads() {
        //存到redis中
        redisTemplate.opsForValue().set("user", "testUsername");
        //获取redis中的数据
        System.out.println(redisTemplate.opsForValue().get("user"));;
    }
}

  自定义redis配置类,因为默认的redis配置会导致中文乱码的问题,所以通过自定义配置来解决这个问题

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.annotation.EnableCaching;
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;
@Configuration //让Spring来加载该类配置
@EnableCaching //开启缓存
public class RedisConfig {
    //编写自己的配置
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();

        //JSON序列化实例
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper obj = new ObjectMapper();//转义对象
        obj.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //2020年8月27日 更新 ==> 系统漏洞,enableDefaultTyping方法已废弃,使用activateDefaultTyping方法
        //obj.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        obj.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(obj);

        //String 序列化实例
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        /**
         * 配置序列化方式
         * 根据需要设置序列化方式
         */
        // key 的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash key的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        //value的序列化方式
        template.setValueSerializer(stringRedisSerializer);
        // hash value的序列化方式
        template.setHashValueSerializer(stringRedisSerializer);

        //配置连接工程
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

  通过自定义的配置进行测试,代码依旧使用上面的代码,区别如下图
在这里插入图片描述
  通过上面的代码及示例,我对redis进行自定义配置以及简单的功能测试演示。但是,上面的代码是通过原生的方式去操作的redis,比较麻烦,所以这里需要再写一个工具类去封装redis的方法,由于写的太多,大家可以再我的git源码上看,文末会给出地址,这里提供两个下面测试用的工具方法

	/**
	 * 存方法redis
	 */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, toJson(value));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 缓存获取
     */
    public String get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key).toString();
    }

    /**
     * Object转成JSON数据
     */
    private String toJson(Object object) {
        if (object instanceof Integer || object instanceof Long || object instanceof Float ||
                object instanceof Double || object instanceof Boolean || object instanceof String) {
            return String.valueOf(object);
        }
        return JSONObject.toJSONString(object);
    }

    /**
     * JSON数据,转成Object
     */
    public <T> List<T> toObject(String json, Class<T> clazz) {
        List<T> list = JSONArray.parseArray(json, clazz);
        return list;
    }

  现在来测试哈我写的工具类

@Test
    public void redisTest() {
        /**
         * 演示将从数据库回去的user存到redis中
         */
        //获取数据
        List<User> user = userService.list();
        // 通过工具保存
        // 本来是打算用list来存的
        // 但是弄了很久都没弄好
        // 所以这里建议使用json字符串来存储
        // 然后转换很方便
        boolean isTrue = redisUtil.set("user", user);

        System.out.println("是否保存成功:" + isTrue);
        //通过工具获取
        String str = redisUtil.get("user");
        List<User> users = redisUtil.toObject(str, User.class);
        for (User u : users) {
            System.out.println(u.getId());
            System.out.println(u.getName());
            System.out.println(u.getEmail());
            System.out.println(u.getAge());
        }
    }

  关于redis的使用就到这里,如果有问题欢迎提出探讨

git地址:https://github.com/peach-tec/peachsys

  2020年8月27日更新
系统漏洞,enableDefaultTyping方法已废弃,使用activateDefaultTyping方法,使用方法,更换enableDefaultTyping方法

obj.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot 中,我们可以通过添加 `spring-boot-starter-data-redis` 依赖来使用 Redis。然后,我们可以通过在 `application.properties` 或 `application.yml` 文件中添加以下属性来配置 Redis RDB 持久化: **application.properties:** ``` # Redis RDB 持久化 spring.redis.database=0 spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.redis.timeout=3000 spring.redis.jedis.pool.max-active=8 spring.redis.jedis.pool.max-idle=8 spring.redis.jedis.pool.min-idle=0 spring.redis.jedis.pool.max-wait=-1 spring.redis.redis-cluster=false spring.redis.sentinel.master= spring.redis.sentinel.nodes= spring.redis.sentinel.password= spring.redis.sentinel.pool.max-active=8 spring.redis.sentinel.pool.max-idle=8 spring.redis.sentinel.pool.min-idle=0 spring.redis.sentinel.pool.max-wait=-1 spring.redis.sentinel.pool.master-name= spring.redis.sentinel.pool.nodes= spring.redis.sentinel.pool.password= spring.redis.cluster.max-redirects=3 spring.redis.cluster.nodes=redis://localhost:6379 spring.redis.cluster.password= spring.redis.cluster.timeout=3000 spring.redis.cluster.max-redirects=3 spring.redis.lettuce.pool.max-active=8 spring.redis.lettuce.pool.max-idle=8 spring.redis.lettuce.pool.min-idle=0 spring.redis.lettuce.pool.max-wait=-1 spring.redis.lettuce.shutdown-timeout=100 spring.redis.lettuce.shutdown-timeout=100 ``` **application.yml:** ``` # Redis RDB 持久化 spring: redis: database: 0 host: localhost port: 6379 password: timeout: 3000 jedis: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1 redis-cluster: false sentinel: master: nodes: password: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1 pool: master-name: nodes: password: cluster: max-redirects: 3 nodes: redis://localhost:6379 password: timeout: 3000 max-redirects: 3 lettuce: pool: max-active: 8 max-idle: 8 min-idle: 0 max-wait: -1 shutdown-timeout: 100 shutdown-timeout: 100 ``` 其中,`spring.redis.database` 表示要使用的 Redis 数据库编号,默认为 0;`spring.redis.host` 和 `spring.redis.port` 表示 Redis 服务器的地址和端口号,默认为 `localhost` 和 `6379`;`spring.redis.password` 表示 Redis 认证密码,默认为空;`spring.redis.timeout` 表示连接 Redis 服务器的超时时间,默认为 3000 毫秒;`spring.redis.jedis.pool.max-active`、`spring.redis.jedis.pool.max-idle`、`spring.redis.jedis.pool.min-idle` 和 `spring.redis.jedis.pool.max-wait` 表示 Jedis 连接池的配置参数,可以根据实际情况进行调整。其他参数的含义可以参考官方文档。 配置完成后,我们可以通过在代码中注入 `RedisTemplate` 或 `StringRedisTemplate` 来进行 Redis 操作。例如: ``` @Autowired private RedisTemplate<String, Object> redisTemplate; public void set(String key, Object value) { redisTemplate.opsForValue().set(key, value); } public Object get(String key) { return redisTemplate.opsForValue().get(key); } ``` 注意,在使用 Redis RDB 持久化时,我们需要在 Redis 服务器的配置文件中开启 RDB 持久化功能。可以通过在配置文件中添加以下内容来开启 RDB 持久化: ``` save 900 1 save 300 10 save 60 10000 ``` 其中,`save` 表示 RDB 持久化的配置项,后面的三个数字分别表示多长时间内有多少次修改操作就会触发一次 RDB 持久化。例如,上面的配置表示如果在 900 秒内有至少一次修改操作、或者在 300 秒内有至少 10 次修改操作、或者在 60 秒内有至少 10000 次修改操作,就会触发一次 RDB 持久化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

華小灼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值