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();
}
}
}
}
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>{
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;
}
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;
}
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;
}
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 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();
LocateRegistry.createRegistry(1111);
Naming.rebind("//localhost:1111/ds", ds);
System.out.println("[RMI]:服务器正在运行。。。");
} catch (Exception e) {
e.printStackTrace();
}
}
}
客户端
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();
}
}
}