(1)POM.XMLは、次のようにJARパッケージを導入します。
<Dependency> groupId> org.springframework.boot </groupid> <artifactid> spring-boot-starter-data-redis </artifactid> </dependency>
(2)プロジェクトの起動クラスを変更し、Annotation @enableCachingを追加し、次のようにキャッシュ機能を有効にします。
パッケージSpringboot; Import org.springframework.boot.springApplication; Import org.springframework.boot.autoconfigure.springbootapplication; import org.springframework.cache.annotation.enablecaching; import org.springframework.scheduling.annotation.enablescheduling;@springbootapplication@enableScheduling@enableCachingPublic Class SpringBootApplication {public static void main(string [] args){springApplication.run(springbootplication.class、args); }}(3)次のように、application.propertiesでRedis接続情報を構成します。
#Redisデータベースインデックス(デフォルトは0)spring.redis.database = 0#redisサーバーアドレスspring.redis.host.host = 172.31.19.2222#Redisサーバー接続ポートspring.redis.port = 6379接続プールの最大ブロッキング待機時間(負の値を使用して制限なし)spring.redis.pool.max-wait = -1#接続プールでの最大アイドル接続spring.redis.pool.max-idle = 8#接続プールの最小アイドル接続spring.redis.pool.min-idle = 0#connentestimeout(milliseconds)spring.timeout = 0 = 0 = 0
(4)次のように、新しいRedis Cache ConfigurationクラスRedisconFigを作成します。
springboot.config; import org.springframework.beans.factory.annotation.value; import org.springframework.cache.cachemanager; import org.springframework.cache.annotation.cachingconfigurerSupport; Import org.springframework.cache.annotation.enablecching springframework.context.annotation.bean; Import org.springframework.context.annotation.configuration; import org.springframework.data.redis.cache.cache.cache.cache.data.data.redis.connection.connection.connection.connection.connection.connection.connection.connection springframework.data.redis.core.redistemplate; Import org.springframework.data.redis.core.stringRedistemplate; import org.springframework.data.redis.serializer.jackson2jsonredisserizer; com.fatsxml.jackson.notation com.fasterxml.jackson.annotation.propertyacsessor; Import com.fasterxml.jackson.databind.objectmapper;/** * Redis Cache Configuration Class * */@Configuration@configuration@enableCachingPublic Class Redisconfig拡張@value( "$ {spring.redis.host}")private string host; @value( "$ {spring.redis.port}")private int port; @value( "$ {spring.redis.timeout}")private int timeout; //カスタムキャッシュキー生成戦略// @bean // public keygenerator keygenerator(){// return new keygenerator(){// @override // public object generate(objectターゲット、java.lang.reflect.methodメソッド、オブジェクト... sb.append(target.getclass()。getname()); // sb.append(method.getname()); // for(object obj:params){// sb.tostring()); //} // return sb.tostring(); //} Cache Manager @Bean Public CacheManager CacheManager(@suppresswarnings( "RawTypes")Redistemplate Redistemplate){RediscaceManager CacheManager = new RediscacheManager(Redistemplate); //キャッシュの有効期限を設定する時間cachemanager.setDefaultExpiration(10000); CacheManagerを返します。 } @bean public redistemplate <string、string> redistemplate(redisconnectionFactory Factory){stringredistemplate = new StringRedistemplate(Factory); SetSerializer(テンプレート); //シリアル化ツールTemplate.afterPropertiesset()を設定します。テンプレートを返します。 } private void setSerializer(stringredistemplateテンプレート){@suppresswarnings({"rawtypes"、 "unchecked"})jackson2jsonredisserializer jackson2jsonredisserializer = new jackson2jsonredisserializer(object.class); ObjectMapper om = new objectMapper(); om.setVisability(propertyaccessor.all、jsonautodetect.visability.any); OM.ENABLEDEFAULTTIPING(objectMapper.defaultting.non_final); jackson2jsonredisserializer.setObjectMapper(OM); template.setValueserializer(Jackson2Jsonredisserializer); }}(5)次のように、新しいUserMapperを作成します。
springboot.dao; Import org.apache.ibatis.annotations.delete; Import org.apache.ibatis.annotations.insert; Import org.apache.ibatis.annotations.mapper; Import org.apache.ibatis.annotations.param; Import org.apaches.Annotations.selection; Import; org.apache.ibatis.annotations.update; import org.springframework.cache.annotation.cacheconfig; Import org.springframework.cache.annotation.cacheevict; Import org.springframework.cache.annotation.cacheput; import.springframework.cacheput springboot.domain.user;@mapper@cacheconfig(cachenames = "users")public interface usermapper {@insert( "inserting user(name、age)values(#{name}、#{age})")int adduser(@param( "name")string name、@age) @Select( "select * from user where id =#{id}")@cachable(key = "#p0")user findbyid(@param( "id")string id); @cacheput(key = "#p0")@update( "uspled user set name =#{name} where id =#{id}")void updatebyid(@param( "id")string id、@param( "name")string name); // Trueとして指定されている場合、メソッドが@Cacheevict(key = "#P0"、allentries = true)と呼ばれる直後にすべてのキャッシュがクリアされます。@cachableは、クエリの結果をRedisにキャッシュします(key = "#p0")redisのキーとして渡された最初のパラメーターを指定します。
@cacheput、キーを指定し、更新された結果をRedisに同期させる
@cacheevict、キーを指定し、キャッシュデータを削除し、allentries = true、メソッドが呼び出された直後にキャッシュがクリアされます
(6)サービスレイヤーとコントローラー層は、前の記事と同じように統合されています。 Redisサーバーを起動します。 Redisサーバーのインストールと起動については、以前のブログを参照できます。アドレスは次のとおりです。
http://www.cnblogs.com/gdpuzxs/p/6623171.html
(7)ログ情報を次のように構成します。
## log4j構成log4j.rootcategory = debug、stdout ##コンソール出力log4j.appender.stdout = org.apache.log4j.consoleappenderlog4j.appender.stdout.layout = org.apache.log4j.patternlayoutlog4j.appender.stdout.layout.conversionPattern =% %c {1}:%l-%m%n(8)Redisキャッシュを確認します
まず、ユーザーテーブルにデータを挿入し、データベースは次のように表示します。
次に、ユーザーテーブルのID = 24でデータを照会しましょう。Guanziコンソールからの情報出力は次のとおりです。
コンソール出力情報を通じて、今回はデータベースクエリが実行され、Redisキャッシュクエリの結果が有効になったことがわかります。次に、ユーザーテーブルのID = 24でデータを再度クエリし、次のようにコンソールを観察します。
コンソールの出力情報を通じて、今回はデータベースクエリを実行するのではなく、Redisキャッシュから照会してクエリ結果を返すことがわかります。次のように、Redisの情報を確認してください。
Method Finduserメソッドは、annotation @cachable(key = "#p0")を使用します。これは、IDがRedisのキー値として使用されることを意味します。データを更新するときは、@cacheput(key = "#p0")を使用してキャッシュデータを更新する必要があります。
要約します
上記は、編集者が紹介したRedisキャッシュを使用したスプリングブートの実装方法です。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します!