Jsdis、Redis和Mysql综合练习(1)

本文介绍了如何构建一个Web工程,利用MyBatis查询数据库并结合Redis进行缓存操作。当用户首次访问时,从MySQL获取用户数据并存入Redis;之后的访问直接从Redis读取。文章详细列出了Maven配置、依赖管理、数据环境、层次包创建、工具类以及DAO、Service和Web层的代码实现。最后展示了查询所有用户信息的JSP页面和实现效果。
摘要由CSDN通过智能技术生成

 

在主页index.jsp向后台servlet发送请求,从数据库中查询所有的用户信息,并输出到浏览器中。

说明:

1.用户第一次访问, redis缓存中没有数据,就从mysql中获取,获取往缓存redis里面放一份

2.用户再次访问,缓存中有数据, 就直接用缓存中获取

3.缓存: redis数据库(运行内存中)

一 我们使用maven搭建web工程

二 导入相关依赖

 <dependencies>
        <!--jedis-->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.7.0</version>
            <type>jar</type>
            <scope>compile</scope>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
        <!--jedis连接池-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.3</version>
        </dependency>


        <!--servlet-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <!--编译 测试需要,运行时不需要-->
            <scope>provided</scope>
        </dependency>

        <!--jsp-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
            <!--依赖范围,编译 测试需要,运行不需要-->
            <scope>provided</scope>
        </dependency>

        <!--mybatis日志包-->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!--mybatis核心包-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>

        <!--mysql驱动-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.18</version>
            <!--编译不需要。测试和运行需要-->
            <scope>runtime</scope>
        </dependency>
        <!--将集合转换为json字符串-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
    </dependencies>

三 导入maven插件

 <!--插件管理-->
    <build>
        <plugins>
            <!--编译插件:jdk1.8-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <!-- put your configurations here -->
                    <!--源码-->
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

 四 配置文件,我们使用配置文件的方式去读取数据

注:所有的配置文件必须放在resources中

五 数据环境,数据库我们采用SQLyog可视化工具进行创建

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(32) DEFAULT NULL,
  `password` varchar(32) DEFAULT NULL,
  PRIMARY KEY (`id`)
);

INSERT INTO `user` VALUES (1, '张三', '123');
INSERT INTO `user` VALUES (2, '李四', '123');
INSERT INTO `user` VALUES (3, '王五', '123');
INSERT INTO `user` VALUES (4, '赵六', '123');
INSERT INTO `user` VALUES (5, '田七', '123');
INSERT INTO `user` VALUES (6, '孙八', '123');
INSERT INTO `user` VALUES (7, '张三丰', '123');
INSERT INTO `user` VALUES (8, '张无忌', '123');
INSERT INTO `user` VALUES (9, '李寻欢', '123');
INSERT INTO `user` VALUES (10, '王维', '123');

六 层次包的创建以及实体类的创建

七 工具类(可有可无,为了方便后期的使用,以及减少代码的冗余性,提高代码的复用性,建议使用.)

7.1jedis数据库连接池工具类

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ResourceBundle;

/*
    Jedis连接池工具类
 */
public class JedisPoolUtil {
    //定义连接池对象
    private static JedisPool pool;

    //1.定义静态代码块:类加载就执行,即读取配置文件
    static {
        //读取配置文件
        //1)创建读取properties文件的类对象
        //参数jedis表示配置文件jedis.properties的文件名
        ResourceBundle bundle = ResourceBundle.getBundle("jedis");

        //2)使用对象bundle调用方法根据key获取配置文件的value
        String maxTotal = bundle.getString("jedis.maxTotal");
        String maxWaitMillis = bundle.getString("jedis.maxWaitMillis");
        String maxIdle = bundle.getString("jedis.maxIdle");
        String host = bundle.getString("jedis.host");
        String port = bundle.getString("jedis.port");



        //2.创建Jedis连接池的配置类对象  JedisPoolConfig配置类
        JedisPoolConfig config = new JedisPoolConfig();

        //修改连接池中的最大连接
//        config.setMaxTotal(10);
        config.setMaxTotal(Integer.parseInt(maxTotal));
        /*
            设置等待最长时间:如果超过了等待的最长时间就报异常
         */
//        config.setMaxWaitMillis(3000);
        config.setMaxWaitMillis(Long.parseLong(maxWaitMillis));
            /*
                设置最大空闲,在实际开发中我们一般将连接池中的最大连接数:maxTotal和最大空闲连接数:maxIdle的值设置为一致
             */
//        config.setMaxIdle(10);
        config.setMaxIdle(Integer.parseInt(maxIdle));
        //3.创建Jedis连接池对象  JedisPool连接池类
//        pool = new JedisPool(config, "localhost", 6379);
        pool = new JedisPool(config, host, Integer.parseInt(port));
    }

    //2.定义静态方法让外界获取Jedis连接对象
    public static Jedis getJedis() {
        Jedis jedis = null;
        if (pool != null) {
            //从连接池中获取Jedis对象
            jedis = pool.getResource();
        }
        //返回对象
        return jedis;
    }
    //3.定义静态方法让外界获取连接池对象
    public static JedisPool getJedisPool(){
        return pool;
    }

7.2 mysql工具类

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 *  会话工厂工具类
        1. 通过静态方法得到一个工厂对象
        2. 通过静态方法得到会话对象
 *
 */
public class SessionFactoryUtils {
    //声明一个工厂对象
    private static SqlSessionFactory factory;
    //在静态代码块中创建会话工厂
    static {
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        //得到输入流
        try(InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");) {
            factory = builder.build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     静态方法得到会话工厂
     */
    public static SqlSessionFactory getSessionFactory() {
        return factory;
    }
    /**
     得到会话对象
     */
    public static SqlSession getSession() {
        return factory.openSession(true);
    }
}

 八 代码实现

dao层:

package com.itheima.sh.dao;

import com.itheima.sh.pojo.User;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface UserMapper {
    //定义查询所有用户的方法
    @Select("select * from user")
    List<User> queryAllUsers();
}

service层:

package com.itheima.sh.survice;

import com.alibaba.fastjson.JSON;
import com.itheima.sh.dao.UserMapper;
import com.itheima.sh.pojo.User;
import com.itheima.sh.utils.JedisPoolUtils;
import com.itheima.sh.utils.SessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import redis.clients.jedis.Jedis;

import java.util.List;

public class UserService {
    public String queryAllUsers() {
        String jsonStr;
        Jedis jedis=null;
        SqlSession session=null;
        try {
            //1 使用工具类获jedis对象
             jedis= JedisPoolUtils.getJedis();
            //2 使用jedis获取key和value值
             jsonStr = jedis.get("USER_LIST");
            if (jsonStr == null) {
                //3 说明redis中没有数据,我们需要从数据库中查询
                //4 获取会话对象
                 session = SessionFactoryUtils.getSession();
                //5 使用会话对象获取接口代理对象
                UserMapper mapper = session.getMapper(UserMapper.class);
                //6 使用接口代理对象调用查询方法
                List<User> list = mapper.queryAllUsers();
                //7 将查询到的list转换成字符串
                jsonStr = JSON.toJSONString(list);
                //8 将获取到的jsonString存储到redis中
                jedis.set("USER_LIST", jsonStr);
            }
        } finally {
            if(jedis!= null){
                jedis.close();
            }
            if(session!= null){
                session.close();
            }
        }
        return jsonStr;
    }
}

web层:

package com.itheima.sh.web;

import com.itheima.sh.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/queryAllUsersServlet")
public class QueryAllUsersServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建业务层对象
        UserService userService = new UserService();
        //2.使用业务层对象调用业务层方法,接收返回的json字符串
        String jsonUserStr = userService.queryAllUsers();
        //3.处理响应乱码
        response.setContentType("text/html;charset=utf-8");
        //4.响应数据
        response.getWriter().print(jsonUserStr);
    }
}

jsp浏览器页面:

<%--
  Created by IntelliJ IDEA.
  User: tiansuo
  Date: 2020-09-13
  Time: 16:01
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>查找用户</title>
</head>
<body>
<h1><a href="/queryAllUsersServlet" style="color: darkgreen">查找所有用户</a></h1>
</body>
</html>

九 实现效果

 

我们启动tomcat服务器,并浏览我们前端页面,就可以看到浏览器端的效果,整个工程较为简单,对于老鸟来说没有什么技术含量,我只为需要者提供,有问题也可以私信我

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值