spring boot 整合 Redis

一、整合过程

1.导入依赖

<dependency>
    <groupId>org.springframework.bootgroupId>
    <artifactId>spring-boot-starter-data-redisartifactId>
dependency>

<dependency>
    <groupId>redis.clientsgroupId>
    <artifactId>jedisartifactId>
dependency>
2.redis配置
redis:
  #地址和端口
  hostName: 124.222.90.72
  port: 6379
  #如果不是局域网和集群可以设置个密码,否则容易被挖矿
  password: 123456
  #可配可不配,因为它的配置类有默认值
  jedis:
    pool:
      max-active: 8
      max-idle: 8
      min-idle: 0
  

spring boot 整合 Redis_第1张图片

3.配置类
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@Slf4j
public class RedisAutoConfig {

    @Bean
    @ConfigurationProperties("spring.redis.jedis.pool")
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    @Bean
    @ConfigurationProperties("spring.redis")
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig) {
        log.info("JedisPoolConfig ==> " + jedisPoolConfig);
        JedisConnectionFactory factory = new JedisConnectionFactory();
        log.info("JedisConnectionFactory ==> " + factory);
        factory.setPoolConfig(jedisPoolConfig);
        return factory;
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(@Qualifier("jedisConnectionFactory") JedisConnectionFactory factory) {
        RedisTemplate redisTemplate = new RedisTemplate();
        log.info("HostName ==> " + factory.getHostName());
        log.info("Port ==> " + factory.getPort());
        redisTemplate.setConnectionFactory(factory);

        //给key和value设置序列化器
//        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setValueSerializer(new StringRedisSerializer());

        return redisTemplate;
    }
}
4.使用
import com.example.springboot.pojo.User;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
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;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@SpringBootTest
class ApplicationTests {
    @Autowired
    DataSource dataSource;

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void test1() throws JsonProcessingException {
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString("1");
        System.out.println(s);
        String s2 = om.writeValueAsString(10);
        System.out.println(s2);
        String s1 = om.writeValueAsString(new User());
        System.out.println(s1);
    }

    @Test
    void contextLoads() {
        System.out.println(dataSource.getClass());
        Connection connection = null;
        try {
            connection = dataSource.getConnection();
            System.out.println(connection);
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    @Test
    public void testSetToString() {
        //默认会将key和value序列化再存入redis中,采用 JDK 序列化器

        redisTemplate.setKeySerializer(new StringRedisSerializer());
//        redisTemplate.setHashKeySerializer(RedisSerializer.string());
//
//        redisTemplate.setValueSerializer(RedisSerializer.json());
        //hash的value序列化方式采用jackson
//        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer;

        redisTemplate.opsForValue().set("name2","kigher222");
        redisTemplate.opsForValue().set("size2",22);
    }

    @Test
    public void testGetToString() {
        //设置取值时候的key和value序列化器
        redisTemplate.setValueSerializer(RedisSerializer.string());
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        Object name = redisTemplate.opsForValue().get("name2");
        System.out.println(name);
        Object size = redisTemplate.opsForValue().get("size2");
        System.out.println(size);
    }

    @Test
    public void testSetToObject() {
        redisTemplate.setKeySerializer(RedisSerializer.string());
        redisTemplate.setValueSerializer(RedisSerializer.json());
        User user = new User(1,"kigher","123456");
        redisTemplate.opsForValue().set("user", user);
        redisTemplate.opsForValue().set("age", 18);
    }

}

二、注意点

1.数据需要经过序列化再存入redis中;
2.如果没有手动设置序列化器,默认会使用jdk序列化器,不过看着不太好看;
3.取值的时候同样会经过反序列化操作,默认同样使用的是jdk序列化器;
4.如果存的是一个对象,可以使用jdk序列化器和json序列化器,但是不能使用string序列化器
5.StringRedisTemplate是RedisTemplate的子类,这个类的源码只是简单的设置了key和value的序列化器都为String序列化器,所以当存储的数据key和value都是String类型的时候就可以使用这个类
6.存取的序列化器需要一致。不是key和value的序列化器必须一致,是存和取时的序列化器必须一致。
  • 存储数据时key的序列化器和取数据时key的序列化器必须一致
  • 存储数据时value的序列化器和取数据时value的序列化器必须一致

如果不遵守这两点,只有两个结果:要么报错,要么乱码

7.redis和spring boot需要版本对应,如果报什么类未找到的异常,多半是版本没有对上
10000. 推荐一篇更好的:https://blog.csdn.net/weixin_42001592/article/details/124054738?spm=1001.2014.3001.5506

你可能感兴趣的:(SSM框架,spring,boot,redis)