中间件作业

RMI 框架 和 jdbc myql数据库使用

1. 服务器
  • 连接mysql数据库
  • rmi接口
  • 使用 gson-2.8.5.jar 和 mysql-8.0.11.jar
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DbUtil {
    private String url="jdbc:mysql://localhost:3306/zuoye?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=Asia/Shanghai";
    private String dbUser="root";
    private String dbPassword="123456";
    private String dbDriver="com.mysql.cj.jdbc.Driver";
    /**
     * 连接对象
     */
    private Connection connection=null;

    public Connection getConnection(){
        try {
            Class.forName(dbDriver);
            connection=DriverManager.getConnection(url,dbUser,dbPassword);
            System.out.println("[SQL]:数据库连接成功,驱动注册成功");
        } catch (ClassNotFoundException e) {
            System.out.println("[SQL]:数据库连接失败,找不到驱动类");
            e.printStackTrace();
        } catch (SQLException throwables) {
            System.out.println("[SQL]:数据库连接失败");
            throwables.printStackTrace();
        }
        return connection;
    }

    public void closeConnection(){
        if(connection!=null){
            try {
                connection.close();
                System.out.println("[SQL]:数据库连接关闭");
            } catch (SQLException throwables) {
                System.out.println("[SQL]:数据库连接关闭失败");
                throwables.printStackTrace();
            }
        }
    }


//    /**
//     * 建立连接
//     */
//    private void initConnection(){
//        try {
//            /* 注册驱动 */
//            /*
//            方法1.注册驱动(3种方法),依赖于驱动jar包的存在,否则无法通过编译
//            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//            方法2:System.setProperties("jdbc.drivers"," com.mysql.cj.jdbc.Driver");
//            方法3:Class.forName("com.mysql.cj.jdbc.Driver");
//            */
//            Class.forName("com.mysql.cj.jdbc.Driver");
//            /* 建立连接 */
//            String jdbc="jdbc:mysql://localhost:3306/zuoye?allowPublicKeyRetrieval=true&useSSL=false&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=CONVERT_TO_NULL&serverTimezone=Asia/Shanghai";
//            conn= DriverManager.getConnection(jdbc,"jeesite","jeesite");
//            /* 创建会话 */
//            statement=conn.createStatement();
//            System.out.println("[SQL]:数据库连接成功");
//        } catch (Exception e) {
//            System.out.println("[SQL]:数据库连接失败");
//            e.printStackTrace();
//        }
//    }
}

import java.sql.Connection;

public class BaseDao<T> {
    private DbUtil dbUtil=new DbUtil();
    public Connection connection= dbUtil.getConnection();
    public void closeConnection(){
        dbUtil.closeConnection();
    }
}
import java.sql.*;
import java.util.LinkedList;
import java.util.List;

public class DBmanager extends BaseDao<StudentScore>{

    /**
     * 数据表Student中添加一条数据
     * @param studentScore
     * @return 是否添加成功
     */
    public boolean addItem(StudentScore studentScore){
        String sql="insert into Student(id,name,score) values(null,?,?)";
        try {
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,studentScore.getName());
            preparedStatement.setFloat(2,studentScore.getScore());
            return preparedStatement.executeUpdate()>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    /**
     * 数据表Student中删除一条数据
     * @param studentScore
     * @return 是否删除成功
     */
    public boolean delItem(StudentScore studentScore){
        String sql="delete from Student where name like ?";
        try {
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,studentScore.getName());
            return preparedStatement.executeUpdate()>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    /**
     * 得到数据库中全部数据列表List
     * @return LinkedList<StudentScore>
     */
    public LinkedList<StudentScore> getList(){
        LinkedList<StudentScore> resultList=new LinkedList<>();
        String sql="select * from Student";
        try {
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            ResultSet resultSet=preparedStatement.executeQuery();
            while(resultSet.next()){
                int id=resultSet.getInt(1);
                String name=resultSet.getString(2);
                float score=resultSet.getFloat(3);
                resultList.add(new StudentScore(id,name,score));
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        return resultList;
    }

    /**
     * 更新表中的一条项目Item
     * @param studentScore
     * @return 是否更新成功
     */
    public boolean updateItem(StudentScore studentScore){
        String sql="update Student set name=?, score=? where id=?";
        try {
            PreparedStatement preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,studentScore.getName());
            preparedStatement.setFloat(2,studentScore.getScore());
            preparedStatement.setInt(3,studentScore.getId());
            return preparedStatement.executeUpdate()>0;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

}

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;

public class StudentScore extends UnicastRemoteObject {
    private int id;
    private String name;
    private float score;

    public StudentScore(int id, String name, float score) throws RemoteException {
        super();
        this.id = id;
        this.name = name;
        this.score = score;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public float getScore() {
        return score;
    }

    public void setScore(float score) {
        this.score = score;
    }
}
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface DataService extends Remote {
    //public double getData() throws RemoteException;
    public String getList() throws RemoteException;
    public boolean addItem(String _name, float _score) throws RemoteException;
    public boolean delItem(String _name, float _score) throws RemoteException;
    public boolean updateItem(int id, String _name, float _score) throws RemoteException;

}

import com.google.gson.Gson;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Calendar;
import java.util.LinkedList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class DataServiceImpl extends UnicastRemoteObject implements DataService {
    private DBmanager dBmanager=new DBmanager();

    public DataServiceImpl() throws RemoteException {
        super();
    }

    @Override
    public String getList() throws RemoteException {
        LinkedList<StudentScore> result=null;
        Callable<LinkedList<StudentScore>> getListTask=new Callable<LinkedList<StudentScore>>() {
            @Override
            public LinkedList<StudentScore> call() throws Exception {
                return dBmanager.getList();
            }
        };
        FutureTask<LinkedList<StudentScore>> futureTask=new FutureTask<>(getListTask);
        new Thread(futureTask).start();

        try {
            result=futureTask.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        String resultJsonString=new Gson().toJson(result);
        return resultJsonString;
    }

    @Override
    public boolean addItem(String _name, float _score) throws RemoteException {
        boolean result=false;
        StudentScore studentScore=new StudentScore(0,_name,_score);
        Callable<Boolean> addItemTask=new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return dBmanager.addItem(studentScore);
            }
        };
        FutureTask<Boolean> futureTask=new FutureTask<>(addItemTask);
        new Thread(futureTask).start();

        try {
            result=futureTask.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public boolean delItem(String _name, float _score) throws RemoteException {
        boolean result=false;
        StudentScore studentScore=new StudentScore(0,_name,_score);
        Callable<Boolean> delItemTask=new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return dBmanager.delItem(studentScore);
            }
        };
        FutureTask<Boolean> futureTask=new FutureTask<>(delItemTask);
        new Thread(futureTask).start();

        try {
            result=futureTask.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public boolean updateItem(int id, String _name, float _score) throws RemoteException {
        boolean result=false;
        StudentScore studentScore=new StudentScore(id,_name,_score);
        Callable<Boolean> updateItemTask=new Callable<Boolean>() {
            @Override
            public Boolean call() throws Exception {
                return dBmanager.updateItem(studentScore);
            }
        };
        FutureTask<Boolean> futureTask=new FutureTask<>(updateItemTask);
        new Thread(futureTask).start();

        try {
            result=futureTask.get();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.rmi.registry.LocateRegistry;

public class MainServer {

    public MainServer() {
    }

    public static void main(String[] args) {
        // 创建并安装安全管理器
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }

        try {
            // 创建远程对象
            DataServiceImpl ds=new DataServiceImpl();

            // 启动注册服务,如果没有这个语句,需要手工启动:开始菜单--运行--rmiregistry,默认端口1099
            LocateRegistry.createRegistry(1111);   //这里,服务端口号可任意指定

            // 远程对象绑定到服务
            Naming.rebind("//localhost:1111/ds", ds);

            System.out.println("[RMI]:服务器正在运行。。。");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

客户端
  • rmi接口
  • 使用 gson-2.8.5.jar
import java.rmi.Remote;
import java.rmi.RemoteException;

public interface DataService extends Remote
{
    public String getList() throws RemoteException;
    public boolean addItem(String _name, float _score) throws RemoteException;
    public boolean delItem(String _name, float _score) throws RemoteException;
    public boolean updateItem(int id, String _name, float _score) throws RemoteException;
}
import com.google.gson.Gson;

import java.rmi.Naming;
import java.rmi.RMISecurityManager;
import java.util.List;
import java.util.Scanner;

public class RmiClient {
    public static void main(String[] args) {
        // 创建并安装安全管理器
        if (System.getSecurityManager() == null) {
            System.setSecurityManager(new RMISecurityManager());
        }
        Scanner scanner=new Scanner(System.in);
        try {
            DataService ds = (DataService) Naming.lookup("//localhost:1111/ds");
            System.out.println("[RMI]: 客户端已接入服务器");
            System.out.println("[TEST]: 测试开始");
            System.out.println("当前服务器中数据:"+ds.getList());
            System.out.println("[TEST]: 插入一条数据");
            System.out.print("请输入学生姓名:");
            String name=scanner.next();
            System.out.println(name);
            System.out.print("请输入学生得分:");
            float score=scanner.nextFloat();
            System.out.println(score);
            ds.addItem(name,score);
            System.out.println("[TEST]: 执行插入操作");
            System.out.println("[TEST]: 查询当前数据库");
            System.out.println("当前服务器中数据:"+ds.getList());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值