av激情亚洲男人的天堂国语,日韩欧美精品一中文字幕,无码av一区二区三区无码,国产又色又爽又刺激的a片,国产又色又爽又刺激的a片

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

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

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

1. Redis注解

Redis注解是在實體類或方法上添加注解的方式,方便地存儲和訪問數(shù)據(jù),可以極大地簡化代碼開發(fā)和維護(hù)。常見的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進(jìn)行緩存非常方便,只需要添加spring-boot-starter-data-redis依賴即可。下面是一個簡單的實例,實現(xiàn)了用戶信息的查詢和更新操作,使用了@Cacheable和@CachePut注解來進(jìn)行緩存操作。

1)添加依賴

org.springframework.boot

spring-boot-starter-data-redis

2)配置redis相關(guān)信息

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表達(dá)式。代碼邏輯很簡單,先從緩存中獲取數(shù)據(jù),如果不存在,則從數(shù)據(jù)庫中查詢,并將結(jié)果放入緩存中;更新操作將緩存中的數(shù)據(jù)清除,并將新的數(shù)據(jù)放入緩存中。

3. 總結(jié)

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

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


文章名稱:Redis簡易注解入門及緩存實踐(redis注解緩存)
文章分享:http://uogjgqi.cn/article/dhheegg.html
掃二維碼與項目經(jīng)理溝通

我們在微信上24小時期待你的聲音

解答本文疑問/技術(shù)咨詢/運(yùn)營咨詢/技術(shù)建議/互聯(lián)網(wǎng)交流