• Redis概述和与SpringBoot的整合


    Redis是一种高性能的键值对存储数据库,它支持多种数据结构,包括字符串、哈希、列表、集合和有序集合等。Redis具有快速、可靠、灵活和可扩展等特点,也被广泛应用于缓存、队列和排行榜等场景。

    SpringBoot是一种基于Spring框架的快速开发脚手架,它支持自动配置、快速开发、易于扩展和集成等特点。SpringBoot提供了对Redis的自动配置支持,可以方便地将Redis集成到SpringBoot项目中。

    通过在SpringBoot项目中添加Spring Data Redis依赖,我们可以直接使用RedisTemplate和RedisRepository等Spring Data Redis提供的API来操作Redis,而不需要编写底层的Redis客户端代码。另外,SpringBoot也提供了对Redis的缓存和Session共享等支持,可以在开发过程中提高效率和可靠性。

    以下是一个简单的Redis与Spring Boot整合的代码案例:

    1. 添加Redis依赖

    pom.xml文件中添加以下Redis依赖:

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-data-redisartifactId>
    4. dependency>

    1. 配置Redis连接信息

    application.properties文件中配置Redis连接信息:

    1. spring.redis.host=localhost
    2. spring.redis.port=6379

    1. 编写RedisTemplate配置类

    config包下创建RedisConfig类,并添加以下代码:

    1. @Configuration
    2. public class RedisConfig {
    3. @Value("${spring.redis.host}")
    4. private String host;
    5. @Value("${spring.redis.port}")
    6. private int port;
    7. @Bean
    8. public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
    9. RedisTemplate redisTemplate = new RedisTemplate<>();
    10. redisTemplate.setConnectionFactory(factory);
    11. redisTemplate.setKeySerializer(new StringRedisSerializer());
    12. redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    13. return redisTemplate;
    14. }
    15. @Bean
    16. public RedisConnectionFactory redisConnectionFactory() {
    17. RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);
    18. return new JedisConnectionFactory(configuration);
    19. }
    20. }

    1. 使用RedisTemplate进行操作

    在需要使用Redis的类中注入RedisTemplate,例如:

    1. @Service
    2. public class UserService {
    3. @Autowired
    4. private RedisTemplate redisTemplate;
    5. public User getUserById(int id) {
    6. String key = "user:" + id;
    7. User user = (User) redisTemplate.opsForValue().get(key);
    8. if (user == null) {
    9. // 从数据库中获取用户信息
    10. user = userDao.getUserById(id);
    11. // 将用户信息存入Redis中
    12. redisTemplate.opsForValue().set(key, user, Duration.ofMinutes(30));
    13. }
    14. return user;
    15. }
    16. }

    以上代码演示了如何将用户信息存入Redis中,并设置30分钟的过期时间。当再次请求获取该用户信息时,先从Redis中获取,如果不存在则从数据库中获取,并将获取到的用户信息存入Redis中。这样可以大大减少数据库的请求次数,提高系统性能。

    以上是一个简单的Redis与Spring Boot整合的代码案例,希望可以帮助到你。

  • 相关阅读:
    Docker的网络模式
    什么是 Linux 进程、线程、轻量级进程和进程状态
    第20章 使用Spring进行事务管理(三)
    LeetCode75——Day4
    想学设计模式、想搞架构设计,先学学UML系统建模吧您
    数据结构题型16-线索二叉树
    海思3559万能平台搭建:在截获的YUV图像上画框
    Swing有几种常用的事件处理方式?如何监听事件?
    将 mixamo 中的动画重定向到 UE 的小白人中
    网络安全:Web 安全 面试题.(SQL注入)
  • 原文地址:https://blog.csdn.net/NanCheng_666/article/details/133777327