Spring Boot + Redis的整合实现

Spring Boot + Redis的整合实现

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

后端实现

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

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

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

properties 复制代码
spring.redis.host=localhost
spring.redis.port=6379

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

java 复制代码
@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;
    }
}

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

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

java 复制代码
@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;
    }
}

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

前台实现

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

vue create frontend

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

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

cd frontend
npm install axios vue-router

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

javascript 复制代码
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');

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

vue 复制代码
<template>
  <div>
    <h2>用户详情</h2>
    <div v-if="user">
      <p>用户名:{{ user.username }}</p>
      <p>年龄:{{ user.age }}</p>
    </div>
    <div v-else>
      <p>用户不存在</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      user: null
    };
  },
  mounted() {
    this.getUser();
  },
  methods: {
    getUser() {
      const userId = this.$route.params.id;
      axios.get(`/api/users/${userId}`).then(response => {
        this.user = response.data;
      });
    }
  }
};
</script>

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

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

javascript 复制代码
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;

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

总结

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

相关推荐
wn53126 分钟前
【Go - 类型断言】
服务器·开发语言·后端·golang
bjzhang7536 分钟前
SpringBoot开发——集成Tess4j实现OCR图像文字识别
spring boot·ocr·tess4j
flying jiang41 分钟前
Spring Boot 入门面试五道题
spring boot
小菜yh42 分钟前
关于Redis
java·数据库·spring boot·redis·spring·缓存
希冀1231 小时前
【操作系统】1.2操作系统的发展与分类
后端
GoppViper1 小时前
golang学习笔记29——golang 中如何将 GitHub 最新提交的版本设置为 v1.0.0
笔记·git·后端·学习·golang·github·源代码管理
爱上语文2 小时前
Springboot的三层架构
java·开发语言·spring boot·后端·spring
荆州克莱2 小时前
springcloud整合nacos、sentinal、springcloud-gateway,springboot security、oauth2总结
spring boot·spring·spring cloud·css3·技术
serve the people2 小时前
springboot 单独新建一个文件实时写数据,当文件大于100M时按照日期时间做文件名进行归档
java·spring boot·后端
小安运维日记3 小时前
Linux云计算 |【第四阶段】NOSQL-DAY1
linux·运维·redis·sql·云计算·nosql