這篇文章將為大家詳細(xì)講解有關(guān)redis通過在Spring Boot項(xiàng)目中使用實(shí)現(xiàn)集中式緩存,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。
創(chuàng)新互聯(lián)建站主營富裕網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營網(wǎng)站建設(shè)方案,APP應(yīng)用開發(fā),富裕h5重慶小程序開發(fā)搭建,富裕網(wǎng)站營銷推廣歡迎富裕等地區(qū)企業(yè)咨詢
1. 利用Spring Initializr來新建一個(gè)spring boot項(xiàng)目
2. 在pom.xml中添加redis、MySQL和cache等相關(guān)依賴。一般情況下,緩存一般是在大規(guī)模數(shù)據(jù)庫存儲(chǔ)下所需要的
org.springframework.boot spring-boot-starter-data-jpa org.springframework.boot spring-boot-starter-cache org.springframework.boot spring-boot-starter-data-redis 1.5.2.RELEASE mysql mysql-connector-java
3. 在application.properties中添加mysql、redis等數(shù)據(jù)庫相關(guān)配置。這里我設(shè)置顯示了每次hibernate讀寫數(shù)據(jù)庫時(shí)所執(zhí)行的sql語句,用于查看數(shù)據(jù)庫的讀取情況
# 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. 編寫一個(gè)簡(jiǎn)單的Entity來存儲(chǔ)示例數(shù)據(jù)。注意,為了使數(shù)據(jù)能夠作為緩存存儲(chǔ)在redis中,一定要將這個(gè)實(shí)體類實(shí)現(xiàn)Serializable接口
@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. 先不設(shè)置User對(duì)象的獲取是利用了緩存機(jī)制,則JPA代碼則如下所示
public interface UserRepository extends JpaRepository{ User findByName(String name); }
6. 編寫主函數(shù)代碼。這里先存儲(chǔ)一個(gè)User實(shí)例對(duì)象,然后讀取兩次這個(gè)對(duì)象,并查看log
@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()); }; } }
運(yùn)行代碼后可以看到log顯示了三次sql語句的使用,一次存入數(shù)據(jù)庫,兩次讀取數(shù)據(jù)庫
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. 在項(xiàng)目中加入緩存的配置
首先在Application中加入緩存配置注解,表示spring boot可以自動(dòng)地檢測(cè)生成是否有可用的緩存配置,這里是根據(jù)依賴判斷可以使用redis作為緩存的數(shù)據(jù)驅(qū)動(dòng)
@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代碼代碼中添加緩存配置注解。這里
@CacheConfig(cacheNames = "users") public interface UserRepository extends JpaRepository{ @Cacheable User findByName(String name); }
再一次運(yùn)行代碼,觀察到log中只有兩次sql語句的使用,一次存入,一次讀取,表明第二次讀取數(shù)據(jù)是從緩存中獲得的而不是從數(shù)據(jù)庫中獲得的
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客戶端查看緩存存儲(chǔ)情況
127.0.0.1:6379> keys * 1) “users:\xac\xed\x00\x05t\x00\x06zhtian”
如此,表明成功地在Spring Boot項(xiàng)目中添加緩存機(jī)制
關(guān)于Redis通過在Spring Boot項(xiàng)目中使用實(shí)現(xiàn)集中式緩存就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。