SSM框架整合Redis数据库


SSM框架整合Redis数据库

由于SSM基本框架之前已经搭建好了,这里就直接开始引入Redis

SSM基本框架链接:IDEA初始化SSM项目(从零开始)-CSDN博客

一、开发环境

项目管理: maven-3.6.0	
后端服务器: tomcat-8.5.5
数据库: mysql-8.0.27
非关系数据库: redis-5.0.5

二、添加Redis配置

1.导入Redis依赖

<!-- jedis依赖 -->
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.7.2</version>
</dependency>
<dependency>
  <groupId>org.springframework.data</groupId>
  <artifactId>spring-data-redis</artifactId>
  <version>1.6.2.RELEASE</version>
</dependency>

2.redis.properties

创建redis.properties文件,存放redis相关数据,以便后续引用

# 本地默认localhost
redis.host=localhost
# 端口号
redis.port=6379		
# 密码
redis.pass=123456
# redis一般会有16各database(0-15),默认为0
redis.database=4
# 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例
redis.maxIdle=300
# 当borrow引入一个jedis实例时,最大的等待时间毫秒,如果超过,则直接报错IedisConnectionException
redis.maxWait=3000
# jedis实例时,提前进入validate操作,如果为true,则为检测好的
redis.testOnBorrow=true

3.spring-redis.xml

创建spring-redis.xml文件,这个配置文件通常包含了与Redis数据库集成所需的各种设置,例如JedisPoolConfig、JedisConnectionFactory以及Spring RedisTemplate的配置。通过这些配置,开发者可以实现Spring应用程序与Redis数据库的交互。

  1. JedisPoolConfig:这是Jedis连接池的配置,用于管理Redis连接的创建和回收,以提高性能和资源利用率。
  2. JedisConnectionFactory:这是Jedis连接工厂,它负责根据JedisPoolConfig提供的配置信息创建和管理Redis连接。
  3. RedisTemplate:这是Spring提供的一个模板类,用于简化Redis操作。它封装了常用的Redis命令,使得在Java代码中可以更加方便地进行Redis数据存取。
<?xml version="1.0" encoding="utf-8" ?>

<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--注解配置-->
    <context:annotation-config/>

    <!--相关配置-->
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>

    </bean>
    <!--连接工厂-->
    <bean id="JedisConnectionFactory"
          class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"
          p:host-name="${redis.host}"
          p:port="${redis.port}"
          p:password="${redis.pass}"
          p:database="${redis.database}"
          p:poolConfig-ref="poolConfig"/>

    <!--此类负责操作redis服务器的工具类-->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="JedisConnectionFactory"/>
    </bean>

</beans>

4.在spring-context.xml文件中引入

注意:这里的location="classpath*:*.properties"要用通配符*,方便spring匹配jdbc.properties和redis.properties配置文件。
错误案例:
    <context:property-placeholder location="classpath*:redis.properties"/>
    <context:property-placeholder location="classpath*:jdbc.properties"/>
    刚开始我是这样配置的,会报错,所有应该是不行
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
    ">
    <!--spring引入外部的配置文件-->
    <context:property-placeholder location="classpath*:*.properties"/>
    <!--通过配置将是spring框架和mybatis框架进行整合-->
    <import resource="spring-mybatis.xml"/>
    <!--通过配置将是spring框架和mybatis框架进行整合-->
    <import resource="spring-redis.xml"/>
    
</beans>

三.测试

User实现序列化接口

由于后续测试中存入redis中的数据是User对象,所有在使用前需要先让User实现序列化接口,就是在User中implements Serializable

package com.demo.pojo;

import java.io.Serializable;

/**
 * @ClassName User
 * @Description
 * @Author Chen
 * @Date 2024/4/14 0:33
 * @Version 1.0
 **/
public class User implements Serializable {
    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

DemoController.java

package com.demo.controller;

import com.demo.pojo.User;
import com.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * @ClassName DemoController
 * @Description
 * @Author Chen
 * @Date 2024/4/13 0:49
 * @Version 1.0
 **/
@Controller
public class DemoController {
    @Autowired
    private DemoService demoService;

    @RequestMapping("/demo")    // 请求路由
    public ModelAndView getUserBy(ModelAndView modelAndView){
        User user = new User();
        // 设置username,以便后面查询
        user.setUsername("admin");
        // 通过username查询用户
        List<User> users = demoService.queryById(user);
        // 将查寻到的用户放进去,传入前端
        modelAndView.addObject("users",users);
        // 设置跳转页面名称
        modelAndView.setViewName("demo");
        return modelAndView;
    }

    @Autowired
    private RedisTemplate redisTemplate;
	// 测试redis
    @RequestMapping("/redis")
    @ResponseBody
    public List<User> getUser(@RequestParam String name){
        String key = "user";
        // 查询redis中是否由user的key
        Boolean hasKey = redisTemplate.hasKey(key);
        // 如果redis中存在就直接从redis中获取结果返回
        if (hasKey){
            return (List<User>) redisTemplate.opsForValue().get(key);
        }else {
            // 否则从数据库中查询结果返回,同时将其存入redis中,以免下次再次请求数据库
            User user = new User();
            user.setUsername(name);
            List<User> users = demoService.queryById(user);
            redisTemplate.opsForValue().set(key,users);
            return users;
        }
    }
}

测试结果

在返回数据处打上断点,调试启动项目,访问对应路径:localhost:8080/SSMDemo_war_exploded/redis?name=admin

发现hasKey为false,表示redis中没有key,本次服务从数据库mysql中获取数据
在这里插入图片描述
让程序运行完,再次访问路径,这次程序停在上一断点处,表示从redis中取数据
在这里插入图片描述
访问对应路径后的前端展示
在这里插入图片描述
redis可视化工具展示
在这里插入图片描述
虽然这里看起来像乱码,但是不影响

  • 43
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
SSM框架整合Redis可以按照以下步骤进行: 1. 首先,在项目的pom.xml文件中添加Redis相关的依赖。这包括redis.clients:jedis和org.springframework.data:spring-data-redis。这些依赖可以通过以下代码添加到pom.xml文件中: ``` <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.10.1</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.1.8.RELEASE</version> </dependency> ``` 2. 接下来,在项目的resources目录下创建一个redis.properties文件,用于配置Redis的相关参数,比如Redis的主机地址、端口号、密码等。 3. 在项目的配置文件中引入Redis的配置。如果是使用Spring Boot,可以在application.properties或application.yml文件中添加Redis的配置。如果是使用传统的Spring框架,可以在applicationContext.xml文件中引入Redis的配置。具体的引入方式可以参考引用\[2\]中的代码示例。 4. 最后,确保项目中导入了SSM相关的jar包,同时也导入了Redis的相关jar包,比如spring-data-redis和jedis。这些jar包可以根据项目的需要进行选择和导入。 通过以上步骤,你就可以在SSM框架中成功整合Redis,实现缓存功能。 #### 引用[.reference_title] - *1* [SSM整合redis](https://blog.csdn.net/qq_45483846/article/details/124224415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SSM框架整合Redis及简单使用](https://blog.csdn.net/L_Shaker/article/details/118827195)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值