Springboot整合Redis

Redis官网
1.安装Redis
windows下安装Redis
2.导入依赖

		<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-data-redisartifactId>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-pool2artifactId>
        dependency>

3.编写配置类RedisConfig

@Configuration
public class RedisConfig {
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
}

4.编写application.yml

spring:
  redis:
    database: 1
    host: 127.0.0.1
    port: 6379
    password:
    timeout: 2000s

    lettuce:
      pool:
        max-wait: 60s
        max-idle: 10
        min-idle: 10
        max-activ: 8

5.测试用例开发

@SpringBootTest
class RedisApplicationTests {
    @Resource
    private RedisTemplate redisTemplate;
   
    @Test
    void testAdd() {
        redisTemplate.opsForValue().set("name","aa");
        String name=(String)redisTemplate.opsForValue().get("name");
        System.out.println(name);
    }

    @Test
    void testUpdate(){
        redisTemplate.opsForValue().set("name","bb");
        String name=(String)redisTemplate.opsForValue().get("name");
        System.out.println(name);
    }

    @Test
    void testDelete(){
        redisTemplate.delete("name");
        String name=(String)redisTemplate.opsForValue().get("name");
        System.out.println(name);
    }

}

Springboot整合Redis_第1张图片

你可能感兴趣的:(Springboot,redis)