文章目录
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数据库的交互。
- JedisPoolConfig:这是Jedis连接池的配置,用于管理Redis连接的创建和回收,以提高性能和资源利用率。
- JedisConnectionFactory:这是Jedis连接工厂,它负责根据JedisPoolConfig提供的配置信息创建和管理Redis连接。
- 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可视化工具展示
虽然这里看起来像乱码,但是不影响