• Spring Boot + Redis的整合实现


    Spring Boot + Redis的整合实现

    在本篇博客中,我们将学习如何使用Spring Boot和Redis进行整合,实现一个简单的缓存功能。我们将分别介绍后端实现和前台实现,并提供详细的代码案例。

    后端实现

    首先,我们需要在Spring Boot项目中添加Redis的依赖项。在pom.xml文件中添加以下依赖:

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

    接下来,我们需要在application.properties文件中配置Redis的连接信息。添加以下配置:

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

    然后,我们需要创建一个Redis配置类,用于配置RedisTemplate和Redis连接工厂。创建一个名为RedisConfig的类,代码如下:

    @Configuration
    @EnableCaching
    public class RedisConfig {
    
        @Autowired
        private Environment environment;
    
        @Bean
        public JedisConnectionFactory jedisConnectionFactory() {
            RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
            config.setHostName(environment.getProperty("spring.redis.host"));
            config.setPort(Integer.parseInt(environment.getProperty("spring.redis.port")));
            return new JedisConnectionFactory(config);
        }
    
        @Bean
        public RedisTemplate<String, Object> redisTemplate() {
            RedisTemplate<String, Object> template = new RedisTemplate<>();
            template.setConnectionFactory(jedisConnectionFactory());
            return template;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22

    在以上代码中,我们使用@EnableCaching注解启用缓存功能。然后,我们通过jedisConnectionFactory方法创建一个Redis连接工厂,并将其配置为RedisTemplate的连接工厂。

    现在,我们可以在服务类中使用Redis进行缓存操作。例如,我们可以在UserService类中添加一个方法,用于获取用户信息。首先,我们需要在方法上添加@Cacheable注解,并指定缓存的名称。然后,我们可以使用redisTemplate对象进行缓存操作。代码如下:

    @Service
    public class UserService {
    
        @Autowired
        private UserRepository userRepository;
    
        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
    
        @Cacheable(value = "users")
        public User getUserById(Long id) {
            String key = "user:" + id;
            User user = (User) redisTemplate.opsForValue().get(key);
            if (user == null) {
                user = userRepository.findById(id).orElse(null);
                redisTemplate.opsForValue().set(key, user);
            }
            return user;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    在以上代码中,我们首先生成一个缓存的key,然后使用redisTemplate对象获取缓存中的用户信息。如果缓存中不存在用户信息,则从数据库中获取,并将其存入缓存中。

    前台实现

    在前台实现中,我们将使用Vue.js来实现一个简单的用户查询页面。首先,我们需要使用Vue CLI创建一个Vue.js项目。打开命令行工具,执行以下命令:

    vue create frontend
    
    • 1

    然后,选择默认配置,等待项目创建完成。

    接下来,我们需要在项目中添加axios和vue-router的依赖项。在命令行中执行以下命令:

    cd frontend
    npm install axios vue-router
    
    • 1
    • 2

    然后,我们需要在src/main.js文件中添加axios和vue-router的配置。修改后的代码如下:

    import Vue from 'vue';
    import App from './App.vue';
    import axios from 'axios';
    import VueAxios from 'vue-axios';
    import router from './router';
    
    Vue.use(VueAxios, axios);
    
    Vue.config.productionTip = false;
    
    new Vue({
      router,
      render: h => h(App)
    }).$mount('#app');
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    现在,我们可以在src/views目录下创建一个名为UserDetail.vue的文件,用于显示用户详情。代码如下:

    
    
    
    
    • 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

    在以上代码中,我们通过this.$route.params.id获取到路由参数中的用户ID,然后使用该ID发送GET请求获取用户的详细信息,并将用户赋值给user变量。如果用户不存在,则显示"用户不存在"的提示信息。

    接下来,我们需要在src/router/index.js文件中添加一个路由规则,用于匹配用户详情页面的URL。修改后的代码如下:

    import Vue from 'vue';
    import VueRouter from 'vue-router';
    import UserList from '../views/UserList.vue';
    import UserDetail from '../views/UserDetail.vue';
    
    Vue.use(VueRouter);
    
    const routes = [
      {
        path: '/users',
        name: 'UserList',
        component: UserList
      },
      {
        path: '/users/:id',
        name: 'UserDetail',
        component: UserDetail
      }
    ];
    
    const router = new VueRouter({
      mode: 'history',
      base: process.env.BASE_URL,
      routes
    });
    
    export default router;
    
    • 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

    现在,我们可以重新启动后端服务和前台页面,测试用户查询和缓存功能。当用户点击用户列表中的"查看详情"按钮时,将跳转到用户详情页面,并显示用户的详细信息。当用户再次点击"查看详情"按钮时,将直接从缓存中获取用户信息,而不再访问数据库。

    总结

    通过本篇博客,我们学习了如何使用Spring Boot和Redis进行整合,实现一个简单的缓存功能。我们介绍了后端实现和前台实现,并提供了详细的代码案例。通过这个实例,我们可以更好地理解和应用Spring Boot和Redis的整合。希望本篇博客对你有所帮助!

  • 相关阅读:
    【iOS】—— MVC模式
    Flask-SQLAlchemy 快速入门
    数据中台体系化建设核心方法论
    3-docker安装centos7
    Redis从入门到精通(二十一)Redis最佳实践(二)mset、pipeline、慢查询优化、内存划分
    【Java集合框架】15——TreeSet 类
    Day119.尚医通:取消预约(微信退款)、就医提醒(定时任务)、预约统计
    计算机毕业设计JavaWeb闲置服装交易平台(源码+系统+mysql数据库+lw文档)
    【ESP32_8266_WiFi (十一)】通过JSON实现物联网数据通讯
    apk反编译和重新打包流程
  • 原文地址:https://blog.csdn.net/2301_79108888/article/details/132823094