SSM整合Redis查询

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_44716935/article/details/102523634

先搭建SSM框架
在这里插入图片描述
在这里插入图片描述

1.pom.xml添加依赖

<!-- 添加redis依赖 -->
   <dependency>
		<groupId>redis.clients</groupId>
		<artifactId>jedis</artifactId>
		<version>2.9.0</version>
	</dependency>

2.spring文件

  • 连接池配置
  • 修改Redis客户端主机号和端口
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 1读取db.properties -->
    <context:property-placeholder location="classpath:db.properties"/>
    
    <!-- 2.配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <!-- 数据库驱动 -->
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    
    <!-- 3.事务管理器,依赖于数据源 -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    
    <!-- 4.开启事务注解 -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- 配置MyBatis工厂 SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据源 -->
        <property name="dataSource" ref="dataSource"/>
        <!-- 指定Mybatis核心配置文件位置 -->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>
    
    <!-- 5.配置mapper扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="dao"/>
    </bean>
    
    <!-- 6.扫描Service -->
    <context:component-scan base-package="service"/>
    
    <!-- 连接池配置 -->
	<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<!-- 最大连接数 -->
		<property name="maxTotal" value="30" />
		<!-- 最大空闲连接数 -->
		<property name="maxIdle" value="10" />
		<!-- 每次释放连接的最大数目 -->
		<property name="numTestsPerEvictionRun" value="1024" />
		<!-- 释放连接的扫描间隔(毫秒) -->
		<property name="timeBetweenEvictionRunsMillis" value="30000" />
		<!-- 连接最小空闲时间 -->
		<property name="minEvictableIdleTimeMillis" value="1800000" />
		<!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
		<property name="softMinEvictableIdleTimeMillis" value="10000" />
		<!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
		<property name="maxWaitMillis" value="1500" />
		<!-- 在获取连接的时候检查有效性, 默认false -->
		<property name="testOnBorrow" value="false" />
		<!-- 在空闲时检查有效性, 默认false -->
		<property name="testWhileIdle" value="false" />
		<!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
		<property name="blockWhenExhausted" value="false" />
	</bean>
	
	<!-- jedis客户端单机版 -->
	<bean id="redisClient" class="redis.clients.jedis.JedisPool">
		<constructor-arg name="host" value="192.168.150.151"></constructor-arg>
		<constructor-arg name="port" value="6379"></constructor-arg>
		<constructor-arg name="poolConfig" ref="jedisPoolConfig"></constructor-arg>
	</bean>
</beans>

3.添加jsp文件到webapp下面

  • 1.springmvc-config.xml视图解析器注释掉,不然访问不了页面
  • 2.加json-jar包。pom.xml中fastjson-jar包注释
    在这里插入图片描述
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>用户管理</h1>
	<form action="/Reds-01/ById" method="post">
		<input type="text" name="id">&nbsp;&nbsp;
		<input type="submit" value="查询用户信息"><br>
	</form>
		
	${student }
</body>
</html>

4.Student

  • 实现Serializable序列化接口
package po;
import java.io.Serializable;
public class Student implements Serializable{
    private Integer id;
    private String stuno;
    private String name;
    private Integer age;  
    public Student() {
		super();
	}
	public Student(Integer id, String stuno, String name, Integer age) {
		super();
		this.id = id;
		this.stuno = stuno;
		this.name = name;
		this.age = age;
	}
	public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getStuno() {
        return stuno;
    }
    public void setStuno(String stuno) {
        this.stuno = stuno;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", stuno=" + stuno + ", name=" + name + ", age=" + age + "]";
    }
}

在这里插入图片描述

5.StudentDao

package dao;
import po.Student;
public interface StudentDao {
    /**
     *  	根据id查询
     * @return
     */
    public Student queryById(Integer id);
}

StudentDao.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="dao.StudentDao">
    <select id="queryById" resultType="student">
    	select * from t_student where id=#{id}
    </select>
</mapper>

6.service

package service;
import po.Student;
public interface StudentService {   
    /**
     *  	根据id查询
     * @return
     */
    public Student queryById(Integer id);
}

service.impl

  • 重要代码逻辑
package service.impl;

import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import dao.StudentDao;
import po.Student;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import service.StudentService;
@Service
@Transactional
public class StudentServiceImpl implements StudentService {
    
    @Autowired
    private StudentDao studentDao;
    
    @Autowired
    private JedisPool jedisPool;

	@Override
	public Student queryById(Integer id) {
		//1.从redis中查询信息,如果有数据就直接返回		
		Jedis resource = jedisPool.getResource();
		String key = "Redis_Student:"+id;
		String msg = resource.get(key); 
		if (msg != null) {
			JSONObject json = new JSONObject();
			System.out.println("Redis中的数据"+msg);
		}
		//2.如果redis中没有数据,从数据库查询信息
		Student student = studentDao.queryById(id);
		System.out.println("student数据库中"+student);
		
		//3.数据库查询到数据在redis中设置key/v值
		resource.set(key, new JSONObject(student).toString()); 
		return student;
	}
}

7.StudentController

package controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import service.StudentService;
@Controller
@RequestMapping("/")
public class StudentController {
	
	@Autowired
	private StudentService studentService;
	
	@RequestMapping("/ById")
	public String studentById(Model model,Integer id) {
		model.addAttribute("student", studentService.queryById(id));
		return "/student.jsp";
	}
}

代码写完

8.配置Redis

第一次查询从数据库中查询
在这里插入图片描述
查询对象set到Redis中
在这里插入图片描述
第二次查询到Redis中查询
在这里插入图片描述
页面数据
在这里插入图片描述

出现的问题

1.浏览器输入控制层地址报空指针异常,解决先访问页面地址获取值
2.404,解决webapp下面jsp要注释掉视图器
3.JSONOb对象放不进对象,解决换json包
完成这案例加深Redis在项目中简单的缓存查询用法,主从复制哨兵模式
提交页面根据id查询,在Redis中有数据就返回前端,
没有数据就到数据库查询,查询到数据保存到Redis
第二次查询就从Redis查询

猜你喜欢

转载自blog.csdn.net/weixin_44716935/article/details/102523634
今日推荐