中國加油,武漢加油!
篇幅較長,配合目錄觀看
案例準備
- 本案例基於springboot篇】二十一. 基於springboot電商項目 六 整合RabbitMQ
1. springboot整合Redis
1.1 shop-temp新建springboot-redis
- Spring Boot DevTools
- Lombok
- 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);
Thread.sleep(1000);
Long time1= stringRedisTemplate.getExpire("email");
System.out.println(time1);
Thread.sleep(4000);
Long time2= stringRedisTemplate.getExpire("email");
System.out.println(time2);
}