springboot篇】二十一. 基於springboot電商項目 七 springboot整合Redis

中國加油,武漢加油!

篇幅較長,配合目錄觀看

案例準備

  1. 本案例基於springboot篇】二十一. 基於springboot電商項目 六 整合RabbitMQ

1. springboot整合Redis

1.1 shop-temp新建springboot-redis

  1. Spring Boot DevTools
  2. Lombok
  3. Spring Data Redis (Access+Driver)

1.2 編寫yml

spring:
  redis:
    host: 192.168.59.100
    password: admin

1.3 Test

package com.wpj;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
class SpringbootRedisApplicationTests {

    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    void contextLoads() {
        redisTemplate.opsForValue().set("age", 20);
        System.out.println(redisTemplate.opsForValue().get("age"));
    }
}

1.3 Test第二種

package com.wpj;

import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
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.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@SpringBootTest
@RunWith(SpringRunner.class)
class SpringbootRedisApplicationTests {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Test
    void contextLoads2() {
        stringRedisTemplate.opsForValue().set("email", "[email protected]");
        System.out.println(stringRedisTemplate.opsForValue().get("email"));
    }

}

在這裏插入圖片描述

2. springboot操縱redis中的事務

@Test
public void testTransaction(){
    redisTemplate.execute(new SessionCallback() {
        @Override
        public Object execute(RedisOperations redisOperations) throws DataAccessException {
            // 開啓事務
            redisOperations.multi();
            try{
                // 操作
                redisOperations.opsForValue().set("email","[email protected]");
                // 事務提交
                redisOperations.exec();
            } catch (Exception e) {
                redisOperations.discard();
                e.printStackTrace();
            }
            return null;
        }
    });
}

3. redis設置超時

@Test
public void testTimeout() throws InterruptedException {
    // 添加一個鍵值對
    stringRedisTemplate.opsForValue().set("email","[email protected]",3, TimeUnit.SECONDS);
    // 給整個鍵值對設置超時時間 10s
//		stringRedisTemplate.expire("email",10, TimeUnit.SECONDS);

    Thread.sleep(1000);
    Long time1= stringRedisTemplate.getExpire("email");
    System.out.println(time1);

    Thread.sleep(4000);
    Long time2= stringRedisTemplate.getExpire("email");
    System.out.println(time2);
}

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章