day40 java Spring 模拟登录逻辑(三)(最终完成版,大概?)


I know, i know
地球另一端有你陪我




一、继续优化

1、引入 redis 作为缓冲层

RedisUtil Redis工具
需要导包
Jedis 3.0.0
使用连接池

/*
        redis 工具类
 */
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisUtil {
    
    
    private static JedisPool jedisPool;
    static{
    
    

        //连接池设置
        JedisPoolConfig jpc = new JedisPoolConfig();
        //连接池数量
        jpc.setMaxTotal(5);
        //最大等待时间
        jpc.setMaxWaitMillis(100);
        //创建连接池
        jedisPool = new JedisPool(jpc,"master",6379);
    }

    public static Jedis getJedis(){
    
    
        return jedisPool.getResource();
    }
}

dao :持久层 / 连接SQL
接口自己写

import com.fgh.spring.mvc.bean.Student;
import com.fgh.spring.mvc.bean.User;
import com.fgh.spring.util.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoMySqlImpl implements UserDao{
    
    
    //连接数据库
    //按照输入的name从数据库中获得对应的数据
    //存储到 user 对象之中,并返回
    public User getuser(String username){
    
    

        User user=null;

        try {
    
    

            Connection conn = JDBCUtil.getConn();

            String sql = "select * from user where username=?";

            PreparedStatement ps = conn.prepareStatement(sql);

            ps.setString(1,username);

            ResultSet rs = ps.executeQuery();

            if(rs.next()){
    
    
                user = new User();
                user.setId(rs.getString("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));

                rs.close();
                ps.close();
                conn.close();
            }
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return user;
    }

    public Student select(String id){
    
    

        Student student = null;

        try {
    
    
            Connection conn = JDBCUtil.getConn();
            PreparedStatement ps = 
            conn.prepareStatement("select * from Student where id=?");

            ps.setString(1,id);
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
    
    

                student = new Student();
                student.setId(rs.getString("id"));
                student.setName(rs.getString("name"));
                student.setBirth(rs.getString("birth"));
                student.setSex(rs.getString("sex"));

                rs.close();
                ps.close();
                conn.close();

            }

        } catch (SQLException e) {
    
    
            e.printStackTrace();
        }
        return student;
    }
}

service :业务逻辑层 / 逻辑验证
接口自己写

import com.fgh.spring.mvc.bean.Student;
import com.fgh.spring.mvc.dao.UserDaoMySqlImpl;
import com.fgh.spring.util.RedisUtil;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;


public class UserService2Impl implements UserService {
    
    

    @Override
    public String checkUser(String username, String password) {
    
    
        if (username == null) {
    
    
            return "请填写用户名";
        }

        UserDaoMySqlImpl ud = new UserDaoMySqlImpl();
        com.fgh.spring.mvc.bean.User user = ud.getuser(username);

        if (user == null) {
    
    
            return "用户名不存在";
        }

        if (!user.getPassword().equals(password)) {
    
    
            return "用户名或密码错误";
        }
        return "登陆成功";
    }
    /*
     * 连接redis
     * hash作为缓存数据结构
     * 通过id查询获取一个map结果
     * map=有数据加TTL  map={}没数据
     * HashMap<String, User> map = new HashMap<String, User>();
     */

    //提前创建对象
    //此处 jedis 不能是静态的,否则一关全关了
    Jedis jedis = RedisUtil.getJedis();
    static UserDaoMySqlImpl userdao=new UserDaoMySqlImpl();

    @Override
    public String selectUser(String id) {
    
    
    //使用 try catch 保证当 redis 数据库断开后
    //依然可以通过连接池,再次连上数据库
        try{
    
    
            Map<String, String> map = jedis.hgetAll("student:" + id);
            // map不等于null 并且map不等于空
            //查到了,先刷新生存时限ttl,再返回数据
            if(map!=null&&!map.isEmpty()){
    
    
                jedis.expire("student:"+id,30);
                return "redis---"+map.toString();
            }
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            jedis.close();
        }


        //如果没有数据,就去 mysql 查
        Student student = userdao.select(id);

        //没查到直接返回
        if(student==null){
    
    
            return "无此用户";
        }

        try{
    
    
            //查到了先存到redis,再返回
            HashMap<String, String> u = new HashMap<>();
            u.put("id",student.getId());
            u.put("name",student.getName());
            u.put("birth",student.getBirth());
            u.put("sex",student.getSex());

            //存到redis,并为其添加生存时限ttl 30s
            //最后返回
            jedis.hmset("student:"+id,u);
            jedis.expire("student:"+id,30);
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            jedis.close();
        }
        return "mysql---"+student.toString();
    }
}

controller :表现层 / 前端交互

import com.fgh.spring.mvc.service.UserService2Impl;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    
    

    @RequestMapping("/login")
    public String login(String username,String password){
    
    
        UserService2Impl us = new UserService2Impl();
        String message = us.checkUser(username, password);
        return message;
    }
    @RequestMapping("/select")
    public String select(String id){
    
    
        UserService2Impl us = new UserService2Impl();
        String message = us.selectUser(id);
        return message;
    }
}

总结

1、在类中方法外,使用带返回值的静态方法,需要先写变量名,才能用 “.” 带出方法

Guess you like

Origin blog.csdn.net/qq_41464008/article/details/121363238