Spring Boot Redis集中式缓存 Spring Boot项目利用Redis实现集中式缓存实例
SkyeBeFreeman 人气:0想了解Spring Boot项目利用Redis实现集中式缓存实例的相关内容吗,SkyeBeFreeman在本文为您仔细讲解Spring Boot Redis集中式缓存的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Spring,Boot,Redis,缓存,Spring,Boot,Redis集中式缓存,下面大家一起来学习吧。
在高并发请求的web服务架构中,随着数据量的提升,缓存机制为绝大多数的后台开发所使用。这篇文章主要介绍如何在Spring Boot项目中为Entity添加利用Redis实现的集中式缓存。
1. 利用Spring Initializr来新建一个spring boot项目
2. 在pom.xml中添加redis、mysql和cache等相关依赖。一般情况下,缓存一般是在大规模数据库存储下所需要的
<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语句,用于查看数据库的读取情况
# 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接口
@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代码则如下所示
public interface UserRepository extends JpaRepository<User, Long> { User findByName(String name); }
6. 编写主函数代码。这里先存储一个User实例对象,然后读取两次这个对象,并查看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()); }; } }
运行代码后可以看到log显示了三次sql语句的使用,一次存入数据库,两次读取数据库
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作为缓存的数据驱动
@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<User, Long> { @Cacheable User findByName(String name); }
再一次运行代码,观察到log中只有两次sql语句的使用,一次存入,一次读取,表明第二次读取数据是从缓存中获得的而不是从数据库中获得的
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客户端查看缓存存储情况
127.0.0.1:6379> keys * 1) “users:\xac\xed\x00\x05t\x00\x06zhtian”
如此,表明成功地在Spring Boot项目中添加缓存机制
加载全部内容