Spring Boot中怎么使用集中式缓存Redis

动手试试User实体的定义

@Entity
@Data
@NoArgsConstructor
public class User implements Serializable {

@Id
@GeneratedValue
private Long id;



private String name;

private Integer age;



public User(String name, Integer age) {
this.name = name;

this.age = age;

}
} User实体的数据访问实现(涵盖了缓存注解)

@CacheConfig(cacheNames = "
users"
)
public interface UserRepository extends JpaRepository<
User, Long>
{

@Cacheable
User findByName(String name);



}

(推荐课程:Spring教程)

SpringBoot中使用集中式缓存Redis

下面开始改造这个项目:

第一步:pom.xml中增加相关依赖:

<
dependency>

<
groupId>
org.springframework.boot<
/groupId>

<
artifactId>
spring-boot-starter-data-redis<
/artifactId>

<
/dependency>

<
dependency>

<
groupId>
org.apache.commons<
/groupId>

<
artifactId>
commons-pool2<
/artifactId>

<
/dependency>

在Spring Boot 1.x的早期版本中,该依赖的名称为spring-boot-starter-redis,所以在Spring Boot 1.x基础教程中与这里不同。

第二步:配置文件中增加配置信息,以本地运行为例,比如:

spring.redis.host=localhost
spring.redis.port=6379
spring.redis.lettuce.pool.max-idle=8
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.max-wait=-1ms
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.shutdown-timeout=100ms

关于连接池的配置,需要注意:

Redis的连接池配置在 1.x 版本中前缀为spring.redis.pool与Spring Boot 2.x有所不同。在 1.x 版本中采用jedis作为连接池,而在 2.x 版本中采用了lettuce作为连接池以上配置均为默认值,实际上生产需进一步根据部署情况与业务要求做适当修改.

再来试试单元测试:

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter54ApplicationTests {

@Autowired
private UserRepository userRepository;



@Autowired
private CacheManager cacheManager;



@Test
public void test() throws Exception {
System.out.println("
CacheManager type : "
+ cacheManager.getClass());



// 创建1条记录
userRepository.save(new User("
AAA"
, 10));



User u1 = userRepository.findByName("
AAA"
);

System.out.println("
第一次查询:"
+ u1.getAge());



User u2 = userRepository.findByName("
AAA"
);

System.out.println("
第二次查询:"
+ u2.getAge());

}


}

执行测试输出可以得到:

CacheManager type : class org.springframework.data.redis.cache.RedisCacheManager
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where nextval=?
Hibernate: insert into user (age, name, id) values (?, ?, ?)
2020-08-12 16:25:26.954 INFO 68282 --- [ main] io.lettuce.core.EpollProvider : Starting without optional epoll library
2020-08-12 16:25:26.955 INFO 68282 --- [ main] io.lettuce.core.KqueueProvider : Starting without optional kqueue library
Hibernate: select user0.id as id10, user0_.age as age20, user0_.name as name30 from user user0 where user0.name=?
第一次查询:10
第二次查询:10

(推荐微课:Spring微课)

可以看到:

  • 第一行输出的CacheManager type为org.springframework.data.redis.cache.RedisCacheManager,而不是上一篇中的EhCacheCacheManager了

  • 第二次查询的时候,没有输出SQL语句,所以是走的缓存获取



  • ——提高Web应用程序的性能和扩展性
    Redis是一个开源内存数据结构存储,可以用来作为缓存工具,提高Web应用程序的性能和可扩展性。Spring Boot集成了Redis,使得使用Redis变得非常容易。在本文中,我们将了解如何在Spring Boot项目中使用Redis缓存,并展示它如何提高Web应用程序的性能和扩展性。
    1. 配置Redis缓存
    要在Spring Boot中使用Redis缓存,需要在项目中添加以下依赖项:
    ```


    org.springframework.boot
    spring-boot-starter-data-redis

    ```
    在application.properties文件中添加以下配置:
    ```
    # Redis服务器地址
    spring.redis.host=localhost
    # Redis服务器端口号
    spring.redis.port=6379
    # Redis服务器连接密码(默认为空)
    spring.redis.password=
    ```
    现在,你已经成功地配置了Redis,并将其与Spring Boot集成了起来。
    2. 使用Redis缓存
    在Spring Boot中,使用Redis非常容易。你只需要添加@EnableCaching注释,并在客户端方法中使用@Cacheable、@CachePut和@CacheEvict注释。这些注释将缓存一些数据,更新缓存,并从缓存中删除数据。
    @Cacheable注释用于缓存结果:
    ```
    @Service
    public class UserServiceImpl implements UserService {
    @Cacheable(value = \"users\")
    @Override
    public User getUserById(int id) {
    return userRepository.findById(id).get();
    }
    }
    ```
    @CachePut注释用于更新缓存:
    ```
    @Service
    public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @CachePut(value = \"users\", key = \"#user.id\")
    @Override
    public User updateUser(User user) {
    return userRepository.save(user);
    }
    }
    ```
    @CacheEvict注释用于从缓存中删除数据:
    ```
    @Service
    public class UserServiceImpl implements UserService {
    @Autowired
    private UserRepository userRepository;
    @CacheEvict(value = \"users\", key = \"#id\")
    @Override
    public void deleteUser(int id) {
    userRepository.deleteById(id);
    }
    }
    ```
    3. Redis缓存的优势
    使用Redis作为缓存工具,有以下优势:
    - 高性能:Redis是一个内存中的数据结构存储,提供了相当快的读和写速度。相比于硬盘存储,内存中的存储速度要快得多。
    - 可扩展性:Redis可以通过主从复制和分片技术实现水平扩展。这使得Redis能够处理更高的访问量和更大的数据集。
    - 持久性:Redis可以将内存中的数据持久化到硬盘驱动器中,以便在服务器崩溃或重启时不会丢失数据。
    - 多种数据类型:Redis支持字符串、列表、哈希、集合和有序集合等多种数据类型,可以为不同的应用程序提供不同类型的数据存储。
    4. 结论
    Redis是一个非常灵活的缓存工具,可以用来提高Web应用程序的性能和扩展性。Spring Boot集成了Redis,使得在项目中使用Redis非常容易。结合Redis的高性能、可扩展性和多种数据类型,可以为Web应用程序带来更好的用户体验和更高的性能。希望本文对你理解Redis的优势并使用Redis缓存有所帮助。