Spring Boot整合Redis

Spring整合Redis

Redis下载地址https://github.com/MicrosoftArchive/redis/releases

Redis五大类型:字符串(String)、哈希/散列/字典(Hash)、列表(List)、集合(Set)、有序集合(sorted set)五种
总括:
RedisTemplate redisTemplate.opsForValue();//操作字符串
RedisTemplate redisTemplate.opsForHash();//操作hash
RedisTemplate redisTemplate.opsForList();//操作list
RedisTemplate redisTemplate.opsForSet();//操作set
RedisTemplate redisTemplate.opsForZSet();//操作有序set

  1. 添加pom依赖

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-redis</artifactId>
        <version>1.5.0.RELEASE</version>
    </dependency>
  2. Redis配置文件

        spring.redis.host=localhost
        spring.redis.port=6379
        #spring.redis.password=123456
        #spring.redis.database=0
        #spring.redis.pool.max-active=8 
        #spring.redis.pool.max-idle=8 
        #spring.redis.pool.max-wait=-1 
        #spring.redis.pool.min-idle=0 
        #spring.redis.timeout
  3. 添加Redis组件类RedisComponent 进行测试

    @Component
    public class RedisComponent {
    
        @Autowired
        private StringRedisTemplate stringRedisTemplate;
    
        public void set(String key, String value) {
    
            ValueOperations<String, String> ops = this.stringRedisTemplate.opsForValue();
            if (!this.stringRedisTemplate.hasKey(key)) {
                ops.set(key, value);
                System.out.println("set key success");
            } else {
                // 存在则打印之前的value值
                System.out.println("this key = " + ops.get(key));
            }
        }
    
        public String get(String key) {
            return this.stringRedisTemplate.opsForValue().get(key);
        }
    
        public void del(String key) {
            this.stringRedisTemplate.delete(key);
        }
    }
  4. 在测试类中写入测试方法

    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class SpringBootDemo10ApplicationTests {
    
        @Autowired
        private RedisComponent redisComponent;
    
        @Test
        public void set() {
            redisComponent.set("redisTest", "hello world");
        }
    
        @Test
        public void get() {
            System.out.println(redisComponent.get("redisTest"));
        }
    
        @Test
        public void del() {
            redisComponent.del("redisTest");
        }
    }
  5. 启动上边下载好的Redis服务,在测试类进行增加、查看和删除操作,可以打开一个redis客户端页面,查看redis中的值
    查看redis中keys
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值