天天看點

SpringBoot使用Redis進行資料緩存的方法

作者:長頸鹿睡覺

SpringBoot預設使用的緩存架構是Simple,如果需要可以更換為使用Redis進行資料緩存。

導入Redis依賴

spring-boot-starter-cache:SpringBoot緩存相關的jar包

spring-boot-starter-data-redis: Redis相關的額jar包

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-cache</artifactId>
</dependency>

<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>           

在啟動類上啟用緩存

在啟動類上應用@EnableCaching注解,啟用SpringBoot緩存。

@SpringBootApplication
@EnableCaching
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}           

設定緩存元件為redis

在application.properties中設定SpringBoot的緩存元件為redis。

spring.cache.type=redis           

設定redis連接配接參數

在application.properties中設定redis的連接配接參數,如果沒有設定使用者密碼,這兩項可不設定。

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.username=user
spring.redis.password=pass           

緩存對象實作序列化接口

如果緩存的值是一個對象,該對象要實作序列化接口,不然往redis裡存的時候會報錯。

@Data
public class User implements Serializable {
    @TableId
    private int userId;
    private String username;
}           

測試

在Service中定義使用緩存的方法。

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Cacheable(value = "mycache", key = "#id")
    public User getUserById(int id) {
        User user = userMapper.selectById(id);
        return user;
    }
}           

在Controller中定義對外的http接口,通路Service的緩存方法。

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @RequestMapping("/{id}")
    public R getUser(@PathVariable int id){
        User user = userService.getUserById(id);
        return new R(0, "查詢成功", user);
    }
}           

啟動項目,在浏覽器中調用http服務。

SpringBoot使用Redis進行資料緩存的方法

第一次通路,緩存是空的,需要查詢資料庫,控制台列印了查詢資料庫的SQL。

SpringBoot使用Redis進行資料緩存的方法

第二次通路,直接從緩存中讀取資料,沒有執行資料庫查詢,控制台沒有列印查詢SQL。說明緩存配置成功。

SpringBoot使用Redis進行資料緩存的方法

緩存配置

可以在application.properties中進行redis緩存的配置

# 是否允許緩存空值
spring.cache.redis.cache-null-values=false
# 是否啟用緩存統計
spring.cache.redis.enable-statistics=true
# 緩存有效期
spring.cache.redis.time-to-live=100s
# 是否在緩存key上使用字首
spring.cache.redis.use-key-prefix=true
# 指定key的字首
spring.cache.redis.key-prefix="cache_"           

如下是配置redis緩存key字首的效果。

SpringBoot使用Redis進行資料緩存的方法

SpringBoot中緩存注解的使用參考:SpringBoot中緩存的使用方法

繼續閱讀