SpringBoot整合Redis
SpringBoot整合Redis
在SpringBoot2.x开始,原来使用的Jedis被替换为了lettuce
jedis:底层采用的是直连,多个线程操作是不安全的,如果想要避免不安全,使用jedis连接池!类似BIO模式
lettuce:采用netty,实例可以在多个线程中共享,不存在线程不安全的情况!可以减少线程数量,类似NIO模式
第一步:导入redis包
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
第二步:配置properties文件
# set redis information
spring.redis.host=localhost
spring.redis.port=6379
第三步:测试
package com.example.redis02springboot;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest
class Redis02SpringbootApplicationTests {
    @Autowired
    RedisTemplate redisTemplate;
    @Test
    void contextLoads() {
        // redisTemplate
        redisTemplate.opsForValue().set("string1", "v1"); //string
        redisTemplate.opsForList().leftPush("list1", 0, "v0"); //list
        redisTemplate.opsForList().rightPush("list1", 1, "v1");
        redisTemplate.opsForSet().add("set1", "v0", "v1", "v2");// set
        redisTemplate.opsForZSet().add("zset1", "v0", 1.1); // zset
        redisTemplate.opsForZSet().add("zset1", "v1", 5.3);
        redisTemplate.opsForHash().put("hash1", "name", "ohmydream"); // hashmap
        redisTemplate.opsForGeo().add("geo1", new Point(116.20, 39.56), 1);// geospatial
        redisTemplate.opsForHyperLogLog().add("pf1", "v1"); // hyperloglog
        redisTemplate.opsForValue().setBit("bitmap", 0, false); // bitmap
        System.out.println(redisTemplate.opsForValue().get("string1"));
        // clear db
//        RedisConnection connection = redisTemplate.getConnectionFactory().getConnection();
//        connection.flushDb(); 
//        connection.flushAll();
    }
}
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号