在高并發請求的web服務架構中,隨著數據量的提升,緩存機制為絕大多數的后臺開發所使用。這篇文章主要介紹如何在Spring Boot項目中為Entity添加利用Redis實現的集中式緩存。
1. 利用Spring Initializr來新建一個spring boot項目
2. 在pom.xml中添加redis、mysql和cache等相關依賴。一般情況下,緩存一般是在大規模數據庫存儲下所需要的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
< dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-jpa</ artifactId > </ dependency > < 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 > < version >1.5.2.RELEASE</ version > </ dependency > < dependency > < groupId >mysql</ groupId > < artifactId >mysql-connector-java</ artifactId > </ dependency > |
3. 在application.properties中添加mysql、redis等數據庫相關配置。這里我設置顯示了每次hibernate讀寫數據庫時所執行的sql語句,用于查看數據庫的讀取情況
1
2
3
4
5
6
7
8
9
10
11
12
13
|
# JPA配置 spring.datasource.url=jdbc:mysql://localhost:3306/your_db spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.jpa.hibernate.ddl-auto=update spring.jpa.properties.hibernate.show_sql=true # Redis配置 spring.session.store-type=redis spring.redis.database=0 spring.redis.host=localhost spring.redis.port=6379 |
4. 編寫一個簡單的Entity來存儲示例數據。注意,為了使數據能夠作為緩存存儲在redis中,一定要將這個實體類實現Serializable接口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
@Entity public class User implements Serializable { @Id @GeneratedValue private long id; @Column (nullable = false ) private String name; @Column (nullable = false ) private int age; public User() {} public User(String name, int age) { this .name = name; this .age = age; } public long getId() { return id; } public void setId( long id) { this .id = id; } public String getName() { return name; } public void setName(String username) { this .name = username; } public int getAge() { return age; } public void setAge( int age) { this .age = age; } } |
5. 先不設置User對象的獲取是利用了緩存機制,則JPA代碼則如下所示
1
2
3
|
public interface UserRepository extends JpaRepository<User, Long> { User findByName(String name); } |
6. 編寫主函數代碼。這里先存儲一個User實例對象,然后讀取兩次這個對象,并查看log
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@SpringBootApplication public class DemoApplication { private Logger logger = LoggerFactory.getLogger( this .getClass()); public static void main(String[] args) { SpringApplication.run(DemoApplication. class , args); } @Bean public CommandLineRunner init(UserRepository userRepository) { return args -> { userRepository.save( new User( "zhtian" , 21 )); logger.info( "第一次讀?。?" + userRepository.findByName( "zhtian" ).getAge()); logger.info( "第二次讀取: " + userRepository.findByName( "zhtian" ).getAge()); }; } } |
運行代碼后可以看到log顯示了三次sql語句的使用,一次存入數據庫,兩次讀取數據庫
1
2
3
4
5
6
|
hibernate: insert into user (age, name) values (?, ?) 2017-06-12 01:44:35.591 INFO 9640 — [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? 2017-06-12 01:44:35.706 INFO 9640 — [ main] ication$$EnhancerBySpringCGLIB$$8a74524d : 第一次讀?。?21 Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? 2017-06-12 01:44:35.706 INFO 9640 — [ main] ication$$EnhancerBySpringCGLIB$$8a74524d : 第二次讀?。?21 |
6. 在項目中加入緩存的配置
首先在Application中加入緩存配置注解,表示spring boot可以自動地檢測生成是否有可用的緩存配置,這里是根據依賴判斷可以使用redis作為緩存的數據驅動
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
@SpringBootApplication @EnableCaching public class DemoApplication { private Logger logger = LoggerFactory.getLogger( this .getClass()); public static void main(String[] args) { SpringApplication.run(DemoApplication. class , args); } @Bean public CommandLineRunner init(UserRepository userRepository) { return args -> { userRepository.save( new User( "zhtian" , 21 )); logger.info( "第一次讀取: " + userRepository.findByName( "zhtian" ).getAge()); logger.info( "第二次讀?。?" + userRepository.findByName( "zhtian" ).getAge()); }; } } |
然后在JPA代碼代碼中添加緩存配置注解。這里
1
2
3
4
5
6
7
|
@CacheConfig (cacheNames = "users" ) public interface UserRepository extends JpaRepository<User, Long> { @Cacheable User findByName(String name); } |
再一次運行代碼,觀察到log中只有兩次sql語句的使用,一次存入,一次讀取,表明第二次讀取數據是從緩存中獲得的而不是從數據庫中獲得的
1
2
3
4
5
|
Hibernate: insert into user (age, name) values (?, ?) 2017-06-12 01:52:41.468 INFO 10680 — [ main] o.h.h.i.QueryTranslatorFactoryInitiator : HHH000397: Using ASTQueryTranslatorFactory Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=? 2017-06-12 01:52:41.589 INFO 10680 — [ main] ication$$EnhancerBySpringCGLIB$$1dda78b5 : 第一次讀?。?21 2017-06-12 01:52:41.589 INFO 10680 — [ main] ication$$EnhancerBySpringCGLIB$$1dda78b5 : 第二次讀取: 21 |
利用Redis客戶端查看緩存存儲情況
1
2
|
127.0.0.1:6379> keys * 1) “users:\xac\xed\x00\x05t\x00\x06zhtian” |
如此,表明成功地在Spring Boot項目中添加緩存機制
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://blog.csdn.net/skyebefreeman/article/details/73086893