日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Redis簡易注解入門及緩存實踐(redis注解緩存)

Redis簡易注解入門及緩存實踐

Redis是一個開源、網(wǎng)絡的、基于內(nèi)存的數(shù)據(jù)結構存儲系統(tǒng),它支持多種數(shù)據(jù)結構,如字符串、哈希表、列表、集合等。Redis具有非常高的性能,支持數(shù)據(jù)的持久化存儲,常常被用作緩存、消息隊列、分布式鎖等場景。本文將介紹Redis的注解使用方式以及如何在Spring Boot項目中使用Redis進行緩存。

1. Redis注解

Redis注解是在實體類或方法上添加注解的方式,方便地存儲和訪問數(shù)據(jù),可以極大地簡化代碼開發(fā)和維護。常見的Redis注解有@Cacheable、@CachePut、@CacheEvict等,它們的作用分別如下:

@Cacheable:在方法執(zhí)行前先檢查緩存中是否有數(shù)據(jù),如果有則直接返回緩存數(shù)據(jù),否則執(zhí)行方法并將返回值存入緩存中。

@CachePut:在方法執(zhí)行后將返回值存入緩存中,與@Cacheable不同的是,@CachePut不會檢查緩存中是否已有數(shù)據(jù),而是直接將返回值存入緩存。

@CacheEvict:用于從緩存中刪除數(shù)據(jù),可以指定刪除的 key 值或清空所有的緩存數(shù)據(jù)。

2. Redis緩存實踐

在Spring Boot項目中使用Redis進行緩存非常方便,只需要添加spring-boot-starter-data-redis依賴即可。下面是一個簡單的實例,實現(xiàn)了用戶信息的查詢和更新操作,使用了@Cacheable和@CachePut注解來進行緩存操作。

1)添加依賴

org.springframework.boot

spring-boot-starter-data-redis

2)配置redis相關信息

spring.redis.host=localhost

spring.redis.port=6379

spring.redis.password=

spring.redis.database=0

3)添加緩存配置類

@Configuration

@EnableCaching

PUBLIC class RedisConfig extends CachingConfigurerSupport {

private Duration timeToLive = Duration.ofHours(1);

@Bean

public RedisCacheManager cacheManager(RedisConnectionFactory connectionFactory) {

RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig()

.serializeValuesWith(RedisSerializationContext.SerializationPr.fromSerializer(new GenericJackson2JsonRedisSerializer()))

.entryTtl(timeToLive);

return RedisCacheManager.builder(connectionFactory)

.cacheDefaults(configuration)

.build();

}

}

4)實體類添加緩存注解

@Data

@NoArgsConstructor

@AllArgsConstructor

public class User {

@Id

private Long id;

private String name;

private Integer age;

}

@Service

@Slf4j

public class UserService {

@Autowired

private UserRepository userRepository;

@Cacheable(value = “users”)

public User getUserById(Long id) {

log.info(“getUserById from db. id:{}”, id);

return userRepository.findById(id).orElse(null);

}

@CachePut(value = “users”, key = “#user.id”)

public User updateUser(User user) {

log.info(“updateUser to db. user:{}”, user);

return userRepository.save(user);

}

}

上述代碼中,@Cacheable和@CachePut注解中的value參數(shù)指定了緩存的名稱,key參數(shù)指定了緩存的鍵值,使用了SpEL表達式。代碼邏輯很簡單,先從緩存中獲取數(shù)據(jù),如果不存在,則從數(shù)據(jù)庫中查詢,并將結果放入緩存中;更新操作將緩存中的數(shù)據(jù)清除,并將新的數(shù)據(jù)放入緩存中。

3. 總結

本文介紹了Redis注解的使用方式以及在Spring Boot項目中使用Redis進行緩存的實踐。Redis注解能夠大大簡化緩存代碼的開發(fā),而Spring Boot的自動化配置和依賴管理也使得Redis緩存的使用變得從容易行。在實際開發(fā)中,需要根據(jù)具體場景選擇不同的注解和配置,以達到最優(yōu)的緩存效果。

成都網(wǎng)站建設選創(chuàng)新互聯(lián)(?:028-86922220),專業(yè)從事成都網(wǎng)站制作設計,高端小程序APP定制開發(fā),成都網(wǎng)絡營銷推廣等一站式服務。


本文題目:Redis簡易注解入門及緩存實踐(redis注解緩存)
網(wǎng)頁鏈接:http://www.5511xx.com/article/dhheegg.html