パラメータ – value : Spring 構成ファイルで定義されたキャッシュの名前。少なくとも 1 つの
パラメータを指定する必要があります。 – key : キャッシュのキー。空でもかまいません。指定されている場合は、SpEL 式に従って書き込む必要があります。指定されていない場合は、メソッドのデフォルトになります。すべてのパラメータが結合されます。
パラメータ – 条件: キャッシュの条件。空にすることができ、SpEL 式を使用して記述され、true または false を返し、true の場合のみキャッシュされます。
おそらく、 SpEL 式が何であるかを知りたいと思われるでしょう。以下に簡単に紹介しましょう:
SpEL 式: Spring 3 では、強力かつ簡潔な方法で値を表現できる Spring Expression Language (Spring Expression Language、SpEL) が導入されています。 Bean のプロパティとコンストラクターのパラメーター、このプロセスで使用される式は実行時に計算されて
値が取得されます。
@Cacheable の構文:
@Cacheable(value=”缓存的名称”,key=”#xxx”)
hset を使用する redis コマンド ライン クライアントの構文は次のとおりです。
hset key field value
@Cacheable アノテーションを使用して、redis の set 関数を呼び出し、生成された値とキーを :: で結合すると以下のようになります。
テストクラス try:
サービスを作成します:
package com.tanhua.server.test;
import com.tanhua.model.db.UserInfo;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
public class UserInfoCacheService {
//根据id查询
@Cacheable(value = "user",key = "#userId")
public UserInfo queryById(Long userId) {
//从数据库查询
System.out.println("从数据库查询");
UserInfo user = new UserInfo();
user.setId(userId);
user.setNickname("ceshi");
return user;
}
}
テストクラスを作成します。
package com.tanhua.server.test;
import com.tanhua.server.AppServerApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest(classes = AppServerApplication.class)
@RunWith(SpringRunner.class)
public class CacheTest {
@Autowired
private UserInfoCacheService userInfoCacheService;
@Test
public void test1() {
for (int i = 1; i <= 5; i++)
System.out.println(userInfoCacheService.queryById(1l));
}
}
1 回目の実行の結果:
2 回目の実行の結果:
ここから、データがキャッシュされ、redis にファイルが生成されたことがわかります。ファイル構造は図に示すとおりです:
user が value 1 が key
間違いがある場合は修正してください