java socket连接池的问题

应用场景:
前端使用JSF作为表现层,浏览器客户端发出请求时我必须先通过socket与集群服务器进行通信之后在将服务器的响应信息进行解析再展现给客户端,为了减少系统开销,我打算在socket这一层使用socket连接池的方式实现。
但是目前遇到一个问题,我从池中取出一个socket后不能判断出该socket是否已经被服务器端关闭了连接,如果服务器端已经关闭了连接,我必须创建一个新的socket,然后对上一次发送失败的请求进行重发处理。
但是,在判断socket是否已经被服务器端关闭这一点,是在是做不到啊!
JAVA API中的socket.isClosed(),socket.isConnected(),以及socket.sendUrgentData()检测的方式都不起作用,麻烦由这方面经验的大哥给些指点。

1个回答

[code="java"]package com.duoguo.util;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;
/**

  • @author shyboy(chao.shen@duoguo.cn) * / public class ConnectionPoolHandler implements Runnable { private Socket socket; @SuppressWarnings("unchecked") private static List pool = new LinkedList(); /*
  • 处理连接 / public void handleConnection() { try { PrintWriter out = new PrintWriter(socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(socket .getInputStream())); String line = in.readLine(); BufferedReader bufferedReader = new BufferedReader(new FileReader( line)); String value = null; while ((value = bufferedReader.readLine()) != null) { out.println(value); } bufferedReader.close(); out.close(); in.close(); } catch (IOException e) { e.printStackTrace(); } } @SuppressWarnings("unchecked") public static void processRequest(Socket socket) { synchronized (pool) { pool.add(pool.size(), socket); pool.notifyAll(); } } /
  • (non-Javadoc) *
  • @see java.lang.Runnable#run()
    */
    @Override
    public void run() {
    while (true) {
    synchronized (pool) {
    while (pool.isEmpty()) {
    try {
    pool.wait();
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    socket = (Socket) pool.remove(0);
    }
    handleConnection();
    }
    }
    }

    /**
    *
    /
    package com.duoguo.socket;
    import java.io.IOException;
    import java.net.ServerSocket;
    import java.net.Socket;
    import com.duoguo.util.ConnectionPoolHandler;
    /
    *

  • @author shyboy(chao.shen@duoguo.cn)
    *
    /
    public class PoolMultiServer {
    private int maxConnections;// 最大连接数
    private int listenerPort;// 监听端口号
    private ServerSocket serverSocket;
    /
    *

  • 构造方法
    *

  • @param maxConnections

  • :最大连接数

    • @param listenerPort
  • :监听端口号
    /
    public PoolMultiServer(int maxConnections, int listenerPort) {
    this.maxConnections = maxConnections;
    this.listenerPort = listenerPort;
    }
    /
    *

  • 接受连接
    /
    public void acceptConnection() {
    try {
    serverSocket = new ServerSocket(listenerPort, maxConnections);
    while (true) {
    Socket socket = serverSocket.accept();
    handleConnection(socket);
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    /
    *

  • 处理连接
    *

  • @param socket

  • :套接字
    /
    public void handleConnection(Socket socket) {
    ConnectionPoolHandler.processRequest(socket);
    }
    public void setUpHandlers() {
    for (int i = 0; i < maxConnections; i++) {
    ConnectionPoolHandler connectionPoolHandler = new ConnectionPoolHandler();
    new Thread(connectionPoolHandler, "处理器" + i).start();
    }
    }
    /
    *

  • @param args
    */
    public static void main(String[] args) {
    PoolMultiServer poolMultiServer = new PoolMultiServer(5, 9999);
    poolMultiServer.setUpHandlers();
    poolMultiServer.acceptConnection();
    }
    }

    /**
    *
    /
    package com.duoguo.socket;
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;
    /
    *

  • @author shyboy(chao.shen@duoguo.cn)
    *
    /
    public class Client {
    private String hostIp;// 客户端主机IP
    private int hostPort;// 客户端主机端口号
    private BufferedReader in;// 客户端输入流
    private PrintWriter out;// 客户端输出流
    /
    *

  • 构造方法
    *

  • @param hostip

  • :IP地址

    • @param hostPort
  • :端口号
    /
    public Client(String hostip, int hostPort) {
    this.hostIp = hostip;
    this.hostPort = hostPort;
    }
    /
    *

  • 建立连接
    /
    public void setUpConnection() {
    try {
    Socket client = new Socket(hostIp, hostPort);
    in = new BufferedReader(new InputStreamReader(client
    .getInputStream()));// 客户端输入流
    out = new PrintWriter(client.getOutputStream());// 客户端输出流
    } catch (UnknownHostException e) {
    System.out.println("找不到相应的主机!");
    e.printStackTrace();
    } catch (IOException e) {
    System.out.println("抛出相应的流异常信息");
    e.printStackTrace();
    }
    }
    /
    *

  • 获取文件
    *

  • @param fileName

  • :文件名称

    • @return String / public String getFile(String fileName) { StringBuilder sb = new StringBuilder(); out.println(fileName); out.flush(); String line = null; try { System.out.println("客户端连接成功!"); while ((line = in.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { System.out.println("文件读入失败!"); e.printStackTrace(); } return sb.toString(); } /*
  • 断开连接
    /
    public void tearDownConnection() {
    try {
    out.close();// 关闭输出流
    in.close();// 关闭输入流
    } catch (IOException e) {
    System.out.println("断开连接失败!");
    e.printStackTrace();
    }
    }
    /
    *

  • @param args
    */
    public static void main(String[] args) {
    Client client = new Client("127.0.0.1", 9999);
    client.setUpConnection();
    String fileContent = client.getFile("D:\hello.txt");
    System.out.println("文件内容为:" + "\n" + fileContent);
    client.tearDownConnection();
    }
    }

作者“shenjichao2009”

[/code]现成的代码

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Socket与连接池
刚学了Socket编程,想拓展一下.与连接池一起用.增加其可用性. 自己写了下,运行没得到想要的结果.不知道错在哪里,所以只能请各位帮忙了. Server端: package pool; import java.net.ServerSocket; import java.net.Socket; public class Server implements Runnable{ protected static int maxLeng; private static int port; private static ServerSocket server; public Server() { } public Server(int port,int maxLength){ this.port=port; this.maxLeng=maxLength; } public void run(){ try { server=new ServerSocket(port,maxLeng);//创建一个最大链接次数为5次的ServerSocket. Socket socket=server.accept(); pool.addSocket(socket); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { Server server=new Server(9090,5); server.run(); } } pool and cilent: package pool; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket; import java.util.LinkedList; import java.util.List; public class pool implements Runnable{ private static List poolList=new LinkedList(); private Socket socket; private String ip; private int port; public pool() { // TODO Auto-generated constructor stub } public pool(String ip,int port){ this.ip=ip; this.port=port; } public static void addSocket(Socket socket){ synchronized (poolList) {//将连接池同步起来 poolList.add(poolList.size(),socket); poolList.notifyAll(); } } public void make(){ try { socket=new Socket(ip,port); File file=new File("e:\\我的工号.txt"); BufferedReader read=new BufferedReader(new InputStreamReader(new FileInputStream(file))); String tempStr=""; String temp=null; PrintWriter pw=new PrintWriter(socket.getOutputStream()); while((temp=read.readLine())!=null){ tempStr+=(temp+"\r"); } pw.write(tempStr); pw.close(); read.close(); } catch (Exception e) { e.printStackTrace(); } } public void run() { while(true){ synchronized (poolList) { while(poolList.isEmpty()){ try { poolList.wait(); } catch (InterruptedException e) { return; } } Socket socket=(Socket)poolList.remove(0); } make(); } } public static void main(String[] args) { add(); } public static void add(){ for(int i=0;i<Server.maxLeng;i++){ pool p=new pool("10.43.9.51",9090); new Thread(p,i+"").start(); } } } 本来是希望通过Socket多线程的读文件.现在运行出现的结果没有报错.也没有任何内容输出.(注:操作步骤没有问题的.)
java socket server
用java编写的一个socket服务端,通过一个tcp测试工具测试这个服务端,发现发送数据给服务端,服务端接收不到,当tcp测试工具断开连接后,测试工具发送的字符串才被服务端接收到,这是为什么? java socket服务端代码 [code="java"] package com.myserver.server; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiThreadServer { private int port = 6666; private ServerSocket serverSocket; private ExecutorService executorService;//线程池 private final int POOL_SIZE = 10;//单个CPU线程池大小 public MultiThreadServer() throws IOException { serverSocket = new ServerSocket(port); //Runtime的availableProcessor()方法返回当前系统的CPU数目. executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * POOL_SIZE); System.out.println("server start"); } public void service() { while (true) { Socket socket = null; try { //接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接 socket = serverSocket.accept(); executorService.execute(new Handler(socket)); Count.add(); System.out.println("client number " + Count.num); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) throws IOException { new MultiThreadServer().service(); } } class Handler implements Runnable { private Socket socket; public Handler(Socket socket) { this.socket = socket; } public void run() { try { System.out.println("a client connect " + socket.getInetAddress() + ":" + socket.getPort()); PrintWriter writer = new PrintWriter(socket.getOutputStream()); writer.println("connect success"); writer.flush(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String readLine = reader.readLine(); while (true) { if (readLine != null) { System.out.println(readLine); readLine = reader.readLine(); } else { break; } } writer.close(); reader.close(); } catch (IOException e) { System.out.println("a client leave"); Count.sub(); System.out.println("client number " + Count.num); } finally { try { if (socket != null) { socket.close(); } } catch (IOException e) { e.printStackTrace(); } } } } class Count { public static int num = 0; public static void add() { num += 1; } public static void sub() { num -= 1; } } [/code] java服务端状态输出如下 server start client number 1 a client connect /127.0.0.1:50437 affff tcp测试工具截图 [img]http://dl.iteye.com/upload/attachment/526919/4726dc79-31b2-3216-8887-de70efdd80cb.jpg[/img] 补充说明: tcp测试工具能够正常连接到服务端,但是文本数据发送,服务端不会实时显示,只有当测试工具断开连接时,这时,服务端才显示刚才测试工具发送的文本数据
远程连接redis连接池总是报错
springboot连接redis 项目启动 服务器上redis是开着的 也能连上 redis.conf中绑定本地id也删除了 就是用这个连接池的时候报错 控制台报如下错误: ``` org.springframework.data.redis.RedisConnectionFailureException: Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:204) at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:348) at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:129) at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:92) at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:79) at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:194) at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:169) at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:91) at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:169) at com.how2java.test.TestRedisOne.testRedisOne(TestRedisOne.java:82) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75) at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86) at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61) at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191) at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50) at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382) at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192) Caused by: redis.clients.jedis.exceptions.JedisConnectionException: Could not get a resource from the pool at redis.clients.util.Pool.getResource(Pool.java:53) at redis.clients.jedis.JedisPool.getResource(JedisPool.java:226) at redis.clients.jedis.JedisPool.getResource(JedisPool.java:16) at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.fetchJedisConnector(JedisConnectionFactory.java:194) ... 38 more Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: connect timed out at redis.clients.jedis.Connection.connect(Connection.java:207) at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:93) at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1767) at redis.clients.jedis.JedisFactory.makeObject(JedisFactory.java:106) at org.apache.commons.pool2.impl.GenericObjectPool.create(GenericObjectPool.java:888) at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:432) at org.apache.commons.pool2.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:361) at redis.clients.util.Pool.getResource(Pool.java:49) ... 41 more Caused by: java.net.SocketTimeoutException: connect timed out at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:589) at redis.clients.jedis.Connection.connect(Connection.java:184) ... 48 more ``` ``` package com.how2java.springboot.web; import java.util.Date; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.how2java.redis.RedisClient; import com.how2java.springboot.pojo.JsonData; import com.how2java.springboot.pojo.UserPojo; import com.how2java.utils.JsonUtils; @RestController @RequestMapping("/api/v1/redis") public class RedisTestController { //得到redis封装类 @Autowired private RedisClient redis; //添加字符串 @GetMapping(value="add") public Object add(){ redis.set("username", "xddddddd"); return JsonData.buildSuccess(); } //通过key值得到value字符串 @GetMapping(value="get") public Object get(){ String value = redis.get("username"); return JsonData.buildSuccess(value); } //将对象通过工具类转成String类型,存入redis中 @GetMapping(value="save_user") public Object saveUser(){ UserPojo user = new UserPojo(1, "abc", "11", new Date()); String userStr = JsonUtils.obj2String(user); boolean flag = redis.set("base:user:11", userStr); return JsonData.buildSuccess(flag); } //通过key值得到value值,让后将value转为对象 @GetMapping(value="find_user") public Object findUser(){ String userStr = redis.get("base:user:11"); UserPojo user = JsonUtils.string2Obj(userStr, UserPojo.class); return JsonData.buildSuccess(user); } } ``` application.propertites ``` ##REDIS (RedisProperties) spring.redis.host=39.105.35.139 spring.redis.port=6397 spring.redis.pool.max-idle=200 spring.redis.pool.min-idle=200 spring.redis.pool.max-active=2000 spring.redis.pool.max-wait=1000 spring.redis.timeout=3000 spring.redis.database=0 spring.redis.password= ``` ``` package com.how2java.redis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; /** * 功能描述:redis工具类 * 对于redisTpl.opsForValue().set(key, value)进行了一次封装,不然每次都要这样保存值 * 而封装后只需:new RedisClient().set(key,value); */ @Component public class RedisClient { @Autowired private StringRedisTemplate redisTpl; //jdbcTemplate // 功能描述:设置key-value到redis中 public boolean set(String key ,String value){ try{ redisTpl.opsForValue().set(key, value); return true; }catch(Exception e){ e.printStackTrace(); return false; } } // 功能描述:通过key获取缓存里面的值 public String get(String key){ return redisTpl.opsForValue().get(key); } } ``` ``` package com.how2java.utils; import java.io.IOException; import org.springframework.util.StringUtils; import com.fasterxml.jackson.databind.ObjectMapper; /** * 字符串转对象,对象转字符串的工具类 * 因为StringRedisTemplate的opsForValue()方法需要key,value都需要String类型,所以当value值存入对象的时候 * 先转成字符串后存入。 */ public class JsonUtils { private static ObjectMapper objectMapper = new ObjectMapper(); //对象转字符串 public static <T> String obj2String(T obj){ if (obj == null){ return null; } try { return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj); } catch (Exception e) { e.printStackTrace(); return null; } } //字符串转对象 public static <T> T string2Obj(String str,Class<T> clazz){ if (StringUtils.isEmpty(str) || clazz == null){ return null; } try { return clazz.equals(String.class)? (T) str :objectMapper.readValue(str,clazz); } catch (IOException e) { e.printStackTrace(); return null; } } } ``` ``` package com.how2java.springboot.pojo; import java.io.Serializable; /** * 这是后端向前端响应的一个包装类 * 一般后端向前端传值会有三个属性 * 1:响应状态 * 2:如果响应成功,把数据放入 * 3: 描述,响应成功描述,或者失败的描述 */ public class JsonData implements Serializable { private static final long serialVersionUID = 1L; private Integer code; // 状态码 0 表示成功,1表示处理中,-1表示失败 private Object data; // 数据 private String msg;// 描述 public JsonData() { } public JsonData(Integer code, Object data, String msg) { this.code = code; this.data = data; this.msg = msg; } // 成功,只返回成功状态码 public static JsonData buildSuccess() { return new JsonData(0, null, null); } // 成功,传入状态码和数据 public static JsonData buildSuccess(Object data) { return new JsonData(0, data, null); } // 失败,传入描述信息 public static JsonData buildError(String msg) { return new JsonData(-1, null, msg); } // 失败,传入描述信息,状态码 public static JsonData buildError(String msg, Integer code) { return new JsonData(code, null, msg); } // 成功,传入数据,及描述信息 public static JsonData buildSuccess(Object data, String msg) { return new JsonData(0, data, msg); } // 成功,传入数据,及状态码 public static JsonData buildSuccess(Object data, int code) { return new JsonData(code, data, null); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public static long getSerialversionuid() { return serialVersionUID; } @Override public String toString() { return "JsonData [code=" + code + ", data=" + data + ", msg=" + msg + "]"; } //提供get和set方法,和toString方法 } ``` ``` package com.how2java.springboot.pojo; import java.util.Date; public class UserPojo { private int age; private String pwd; private String phone; private Date createTime; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public UserPojo() { super(); } public UserPojo(int age, String pwd, String phone, Date date) { super(); this.age = age; this.pwd = pwd; this.phone = phone; this.createTime = date; } } ```
httpclient怎么设置连接池连接等待时间
连接满时,会处于连接池等待状态,怎么设置连接池等待时间,避免造成长时间等待 求大神解答,急!在线等!!!! /*读取超时*/ private final static int SOCKET_TIMEOUT = 50000; /*连接超时*/ private final static int CONNECTION_TIMEOUT = 50000; /*每个HOST的最大连接数量*/ private final static int MAX_CONN_PRE_HOST = 2; /*连接池的最大连接数*/ private final static int MAX_CONN = 60; /*连接池*/ private final static HttpConnectionManager httpConnectionManager; static{ httpConnectionManager = new MultiThreadedHttpConnectionManager(); HttpConnectionManagerParams params = httpConnectionManager.getParams(); params.setConnectionTimeout(CONNECTION_TIMEOUT); params.setSoTimeout(SOCKET_TIMEOUT); params.setDefaultMaxConnectionsPerHost(MAX_CONN_PRE_HOST); params.setMaxTotalConnections(MAX_CONN); }
Java多线程服务器问题,executorservice的用法
创建了一个Java多线程服务器,通过socket连接不断接收大量设备(客户端)传输过来的信息 ``` // 创建可以容纳4个线程的线程池 ExecutorService fixedThreadPool = Executors.newFixedThreadPool(4); ``` 当连接数达到4个时出现了阻塞状态,求解怎么解决,怎么在完成一次数据解析后释放工作线程接收下一个连接,有点卡壳
怎么用java代码测试serversocket的最大可连接数
不使用JMeter等压力测试软件,怎么使用java代码测试serversocket的最大可连接数? 服务器是利用serversocket,每次接收到一个socket,就提交给线程池,以下是客户端的代码 package Client; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.net.Socket; import java.net.UnknownHostException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class Client { public static void main(String[] args) { initFile("test.txt"); initFile("time.txt"); ExecutorService pool = Executors.newFixedThreadPool(1000); for (int i = 0; i < 3000; i++) { pool.submit(new Thread() { @Override public void run() { sendSocket(); } }); } pool.shutdown(); } public static void initFile(String fileName) { File file = new File(fileName); if (file.exists()) file.delete(); } public static void sendSocket() { Socket socket = null; try { socket = new Socket("127.0.0.1", 14); long startTime = System.currentTimeMillis(); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String string = ""; String line; while ((line = reader.readLine()) != null) { string += line; } string += "\r\n"; long endTime = System.currentTimeMillis(); FileOutputStream fos = new FileOutputStream("test.txt", true); fos.write(string.getBytes()); fos.flush(); fos.close(); fos = new FileOutputStream("time.txt", true); String time = (endTime - startTime) + "ms\r\n"; fos.write(time.getBytes()); fos.flush(); fos.close(); } catch (UnknownHostException e) { System.out.println("UnknownHostException"); } catch (IOException e) { System.out.println("IOException1"); } finally { if (socket != null) try { socket.close(); } catch (IOException e) { System.out.println("IOException2"); } } } } 发现客户端数量为3000的时候就会打印IOEXCEPTION1,但是服务器那边却没有崩溃。到底该怎么测试最大可连接数呢?
Android socket通讯客户端连不上服务器问题,以及发送消息程序就闪退
原本以为是线程问题但是好像又不是,实在找不到怎么弄了 这是客户端: package com.chiaki.mysocketobject; import android.content.Intent; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ListView; import android.widget.TextView; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; import java.util.ArrayList; import java.util.List; public class ChatActivity extends AppCompatActivity implements Runnable{ private static final String HOST = "172.16.2.54"; private static final int PORT = 12345; private MsgAdapter adapter; private ListView msgListView; private List<Msg> msgList=new ArrayList<Msg>(); private ImageButton send; private ImageButton connect; private EditText edit; private TextView ctext; private Socket socket; private BufferedReader in = null; private PrintWriter out = null; private String content = ""; private StringBuilder sb = null; public Handler handler = new Handler() { public void handleMessage(Message msg) { if (msg.what == 0x123) { sb.append(content); ctext.setText(sb.toString()); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); adapter=new MsgAdapter(ChatActivity.this,R.layout.chat_list_view,msgList); ImageButton back = (ImageButton)findViewById(R.id.back); ImageButton voiceButton = (ImageButton)findViewById(R.id.voiceButton); connect = (ImageButton)findViewById(R.id.connectButton); send = (ImageButton)findViewById(R.id.send); edit = (EditText)findViewById(R.id.edit); ctext = (TextView)findViewById(R.id.chattext); msgListView=(ListView)findViewById(R.id.msg_list_view); sb = new StringBuilder(); msgListView.setAdapter(adapter); // 点击按钮实例化Socket对象,与服务端进行连接,获取输入输出流 // 连接服务器,要在子线程中 connect.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new Thread() { @Override public void run() { super.run(); try { // 创建socket,连接服务器 socket = new Socket(HOST, PORT);//连接服务器 in = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));//接收消息的流对象 out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);//发送消息的流对象 } catch (Exception e) { e.printStackTrace(); } } }.start(); } }); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(ChatActivity.this,SocketActivity.class); startActivity(intent); } }); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String con=edit.getText().toString(); edit.setText(""); if (socket.isConnected()) { if (!socket.isOutputShutdown()) { out.println(con);//点击按钮发送消息 } } } }); //启动线程,连接服务器,并用死循环守候,接收服务器发送过来的数据 new Thread(ChatActivity.this).start(); } // 重写run方法,在该方法中输入流的读取 public void run() { try { while (true) { //死循环守护,监控服务器发来的消息 if (socket.isConnected()) { //如果服务器没有关闭 if (!socket.isInputShutdown()) { //连接正常 if ((content = in.readLine()) != null) { //如果输入流没有断开 content += "\n"; //读取接收的信息 handler.sendEmptyMessage(0x123); //会发送一个空消息,但是指定了Message的what属性 } } } } } catch (Exception e) { e.printStackTrace(); } } } 这是layout文件主要的控件: <ImageButton //建立连接按钮 android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@android:drawable/checkbox_on_background" android:id="@+id/connectButton" android:layout_alignParentStart="true" android:layout_below="@+id/edit" /> <TextView //显示消息 android:text="TextView" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/chattext" /> <ImageButton //编辑消息 android:layout_width="wrap_content" android:layout_height="wrap_content" app:srcCompat="@android:drawable/ic_btn_speak_now" android:id="@+id/voiceButton" android:layout_below="@+id/edit" android:layout_centerHorizontal="true" /> <ImageButton //发送消息 android:layout_width="wrap_content" android:layout_height="40dp" app:srcCompat="@android:drawable/ic_menu_send" android:id="@+id/send" android:backgroundTint="?attr/colorButtonNormal" android:layout_alignParentBottom="true" android:layout_alignParentEnd="true" /> 这是服务端: import java.io.DataInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; public class Server { // 定义相关的参数,端口,存储Socket连接的集合,ServerSocket对象 // 以及线程池 private static final int PORT = 12345; private List<Socket> mList = new ArrayList<Socket>(); private ServerSocket server = null; private ExecutorService myExecutorService = null; public static void main(String[] args) { new Server(); } public Server() { try { server = new ServerSocket(PORT); // 创建线程池 myExecutorService = Executors.newCachedThreadPool(); System.out.println("服务端运行中...\n"); Socket client = null; while (true) { client = server.accept(); mList.add(client); myExecutorService.execute(new Service(client)); } } catch (Exception e) { e.printStackTrace(); } } class Service implements Runnable { private Socket socket; private BufferedReader in = null; private String msg = ""; public Service(Socket socket) { this.socket = socket; try { in = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("用户:" + this.socket.getInetAddress() + "~加入了聊天室" + "当前在线人数:" + mList.size()); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { try { while (true) { if ((msg = in.readLine()) != null) { if (msg.equals("bye")) { System.out.println("~~~~~~~~~~~~~"); mList.remove(socket); in.close(); System.out.println("用户:" + socket.getInetAddress() + "退出:" + "当前在线人数:" + mList.size()); socket.close(); break; } else { System.out.println(socket.getInetAddress() + " 说: " + msg); this.sendmsg(); } } } } catch (Exception e) { e.printStackTrace(); } } // 为连接上服务端的每个客户端发送信息 public void sendmsg() { int num = mList.size(); for (int index = 0; index < num; index++) { Socket mSocket = mList.get(index); PrintWriter pout = null; try { pout = new PrintWriter( new BufferedWriter(new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8")), true); pout.println(msg); } catch (IOException e) { e.printStackTrace(); } } } } }
spring配置mongodb连接池
在mongo中查询数据的时候偶尔会出现下面的错误: com.mongodb.DBPortPool gotError 警告: emptying DBPortPool to /192.168.xx.xx:30030 b/c of error java.net.SocketException: Connection reset by peer: socket write error
Connection reset by peer: socket write error
这个错误在网上能查到很多结果,但是我参照做都没有效果,现在问题依然存在,详细的错误信息如下 2014-05-01 21:46:37 -close connection error java.sql.SQLRecoverableException: IO 错误: Connection reset by peer: socket write error at oracle.jdbc.driver.T4CConnection.logoff(T4CConnection.java:587) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.jdbc.driver.PhysicalConnection.close(PhysicalConnection.java:4011) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at com.alibaba.druid.filter.FilterChainImpl.connection_close(FilterChainImpl.java:167) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.filter.stat.StatFilter.connection_close(StatFilter.java:254) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.filter.FilterChainImpl.connection_close(FilterChainImpl.java:163) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl.close(ConnectionProxyImpl.java:115) ~[druid-1.0.0.jar:1.0.0] at com.alibaba.druid.util.JdbcUtils.close(JdbcUtils.java:82) ~[druid-1.0.0.jar:1.0.0] at com.alibaba.druid.pool.DruidDataSource.discardConnection(DruidDataSource.java:967) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.pool.DruidDataSource.getConnectionDirect(DruidDataSource.java:934) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:4534) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.filter.stat.StatFilter.dataSource_getConnection(StatFilter.java:661) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.filter.FilterChainImpl.dataSource_connect(FilterChainImpl.java:4530) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:880) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:872) [druid-1.0.0.jar:1.0.0] at com.alibaba.druid.pool.DruidDataSource.getConnection(DruidDataSource.java:97) [druid-1.0.0.jar:1.0.0] at org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource.getConnection(AbstractRoutingDataSource.java:162) [payplat-dacq-1.0-SNAPSHOT.jar:na] at org.springframework.jdbc.datasource.DataSourceUtils.doGetConnection(DataSourceUtils.java:111) [payplat-dacq-1.0-SNAPSHOT.jar:na] at org.springframework.jdbc.datasource.DataSourceUtils.getConnection(DataSourceUtils.java:77) [payplat-dacq-1.0-SNAPSHOT.jar:na] at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:382) [payplat-dacq-1.0-SNAPSHOT.jar:na] at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:456) [payplat-dacq-1.0-SNAPSHOT.jar:na] at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:464) [payplat-dacq-1.0-SNAPSHOT.jar:na] at com.payplat.util.jdbc.other.impl.JdbcServerImpl.meterList(JdbcServerImpl.java:88) [payplat-dacq-1.0-SNAPSHOT.jar:na] at com.smotive.action.DasControl.meterList(DasControl.java:52) [DasControl.class:na] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.7.0_45] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) ~[na:1.7.0_45] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.7.0_45] at java.lang.reflect.Method.invoke(Method.java:606) ~[na:1.7.0_45] at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219) [spring-web-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132) [spring-web-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:920) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:816) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:617) [servlet-api.jar:na] at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:801) [spring-webmvc-3.2.1.RELEASE.jar:3.2.1.RELEASE] at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) [servlet-api.jar:na] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) [catalina.jar:6.0.35] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:6.0.35] at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) [spring-web-3.2.1.RELEASE.jar:3.2.1.RELEASE] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) [catalina.jar:6.0.35] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:6.0.35] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) [catalina.jar:6.0.35] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) [catalina.jar:6.0.35] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) [catalina.jar:6.0.35] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [catalina.jar:6.0.35] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [catalina.jar:6.0.35] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) [catalina.jar:6.0.35] at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:877) [tomcat-coyote.jar:6.0.35] at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:594) [tomcat-coyote.jar:6.0.35] at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1675) [tomcat-coyote.jar:6.0.35] at java.lang.Thread.run(Thread.java:744) [na:1.7.0_45] Caused by: java.net.SocketException: Connection reset by peer: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) ~[na:1.7.0_45] at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:113) ~[na:1.7.0_45] at java.net.SocketOutputStream.write(SocketOutputStream.java:159) ~[na:1.7.0_45] at oracle.net.ns.DataPacket.send(DataPacket.java:210) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.net.ns.NetOutputStream.flush(NetOutputStream.java:230) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.net.ns.NetInputStream.getNextPacket(NetInputStream.java:321) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.net.ns.NetInputStream.read(NetInputStream.java:268) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.net.ns.NetInputStream.read(NetInputStream.java:190) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.net.ns.NetInputStream.read(NetInputStream.java:107) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CSocketInputStreamWrapper.readNextPacket(T4CSocketInputStreamWrapper.java:124) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CSocketInputStreamWrapper.read(T4CSocketInputStreamWrapper.java:80) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CMAREngine.unmarshalUB1(T4CMAREngine.java:1137) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:350) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.jdbc.driver.T4C7Ocommoncall.doOLOGOFF(T4C7Ocommoncall.java:61) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] at oracle.jdbc.driver.T4CConnection.logoff(T4CConnection.java:574) ~[ojdbc6-11.2.0.3.0.jar:11.2.0.3.0] ... 55 common frames omitted 根据网上的说法,出现的Connection reset by peer: 原因可能是多方面的,不过更常见的原因是: ①:服务器的并发连接数超过了其承载量,服务器会将其中一些连接Down掉; ②:客户关掉了浏览器,而服务器还在给客户端发送数据; ③:浏览器端按了Stop 2、3点可以排除,第一点让我觉得确实有问题,但是不知道该如何下手,还有一个问题就是,这个异常不是我手动捕获的,在我try catch前这个异常已经抛出,这个让我不解
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]
idea中springboot内置tomcat起不起来 pom.xml: <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.2.1.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.aipuer</groupId> <artifactId>spring-boot</artifactId> <version>0.0.1-SNAPSHOT</version> <name>spring-boot</name> <description>Demo project for Spring Boot</description> <properties> <java.version>11</java.version> </properties> <dependencies> <!-- springBoot 的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- springBoot 的启动器 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <!-- Mybatis 启动器 --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>1.1.1</version> </dependency> <!-- mysql 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- druid 数据库连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.9</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>1.5.9.RELEASE</version> </plugin> </plugins> </build> </project> 错误代码: 2019-12-03 10:08:21.181 INFO 7936 --- [ main] com.aipuer.springboot.Application : Starting Application on PC-20191121IKBV with PID 7936 (E:\java\develop\javacode\spring-boot\target\classes started by Administrator in E:\java\develop\javacode\spring-boot) 2019-12-03 10:08:21.183 INFO 7936 --- [ main] com.aipuer.springboot.Application : No active profile set, falling back to default profiles: default 2019-12-03 10:08:21.554 WARN 7936 --- [ main] o.m.s.mapper.ClassPathMapperScanner : No MyBatis mapper was found in '[com.aipuer.springboot]' package. Please check your configuration. 2019-12-03 10:08:21.839 INFO 7936 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http) 2019-12-03 10:08:21.844 INFO 7936 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-12-03 10:08:21.844 INFO 7936 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.27] 2019-12-03 10:08:21.888 ERROR 7936 --- [ main] org.apache.catalina.core.ContainerBase : A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]] at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:na] at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na] at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.startup.Tomcat.start(Tomcat.java:459) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:107) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:88) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:438) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:191) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:153) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at com.aipuer.springboot.Application.main(Application.java:10) ~[classes/:na] Caused by: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]] at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardPipeline.startInternal(StandardPipeline.java:176) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5063) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na] at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) ~[tomcat-embed-core-9.0.27.jar:9.0.27] ... 29 common frames omitted Caused by: java.lang.NoSuchMethodError: 'java.lang.String javax.servlet.ServletContext.getVirtualServerName()' at org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1220) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] ... 39 common frames omitted 2019-12-03 10:08:21.889 ERROR 7936 --- [ main] org.apache.catalina.core.ContainerBase : A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: A child container failed during start at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:na] at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardEngine.startInternal(StandardEngine.java:262) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardService.startInternal(StandardService.java:421) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardServer.startInternal(StandardServer.java:930) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.startup.Tomcat.start(Tomcat.java:459) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.initialize(TomcatWebServer.java:107) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatWebServer.<init>(TomcatWebServer.java:88) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getTomcatWebServer(TomcatServletWebServerFactory.java:438) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory.getWebServer(TomcatServletWebServerFactory.java:191) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.createWebServer(ServletWebServerApplicationContext.java:180) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.onRefresh(ServletWebServerApplicationContext.java:153) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:544) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE] at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE] at com.aipuer.springboot.Application.main(Application.java:10) ~[classes/:na] Caused by: org.apache.catalina.LifecycleException: A child container failed during start at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:928) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:841) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na] at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) ~[tomcat-embed-core-9.0.27.jar:9.0.27] ... 21 common frames omitted Caused by: java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]] at java.base/java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[na:na] at java.base/java.util.concurrent.FutureTask.get(FutureTask.java:191) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:916) ~[tomcat-embed-core-9.0.27.jar:9.0.27] ... 29 common frames omitted Caused by: org.apache.catalina.LifecycleException: Failed to start component [NonLoginAuthenticator[StandardEngine[Tomcat].StandardHost[localhost].TomcatEmbeddedContext[]]] at org.apache.catalina.util.LifecycleBase.handleSubClassException(LifecycleBase.java:440) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:198) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardPipeline.startInternal(StandardPipeline.java:176) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5063) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1384) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1374) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[na:na] at org.apache.tomcat.util.threads.InlineExecutorService.execute(InlineExecutorService.java:75) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at java.base/java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:140) ~[na:na] at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:909) ~[tomcat-embed-core-9.0.27.jar:9.0.27] ... 29 common frames omitted Caused by: java.lang.NoSuchMethodError: 'java.lang.String javax.servlet.ServletContext.getVirtualServerName()' at org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1220) ~[tomcat-embed-core-9.0.27.jar:9.0.27] at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183) ~[tomcat-embed-core-9.0.27.jar:9.0.27] ... 39 common frames omitted 2019-12-03 10:08:21.889 INFO 7936 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2019-12-03 10:08:21.900 WARN 7936 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat 2019-12-03 10:08:21.906 INFO 7936 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2019-12-03 10:08:21.909 ERROR 7936 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPLICATION FAILED TO START *************************** Description: An attempt was made to call a method that does not exist. The attempt was made from the following location: org.apache.catalina.authenticator.AuthenticatorBase.startInternal(AuthenticatorBase.java:1220) The following method did not exist: 'java.lang.String javax.servlet.ServletContext.getVirtualServerName()' The method's class, javax.servlet.ServletContext, is available from the following locations: jar:file:/E:/java/develop/javacode/spring-boot/lib/javaee.jar!/javax/servlet/ServletContext.class jar:file:/E:/maven/maven_repository/org/apache/tomcat/embed/tomcat-embed-core/9.0.27/tomcat-embed-core-9.0.27.jar!/javax/servlet/ServletContext.class It was loaded from the following location: file:/E:/java/develop/javacode/spring-boot/lib/javaee.jar Action: Correct the classpath of your application so that it contains a single, compatible version of javax.servlet.ServletContext Disconnected from the target VM, address: '127.0.0.1:52758', transport: 'socket' Process finished with exit code 1
java c3p0时不时的报异常,谁碰到过
** BEGIN NESTED EXCEPTION ** java.net.SocketException MESSAGE: Socket input is already shutdown STACKTRACE: java.net.SocketException: Socket input is already shutdown at java.net.Socket.shutdownInput(Socket.java:1361) at com.mysql.jdbc.MysqlIO.quit(MysqlIO.java:1683) at com.mysql.jdbc.ConnectionImpl.realClose(ConnectionImpl.java:4388) at com.mysql.jdbc.ConnectionImpl.cleanup(ConnectionImpl.java:1368) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2654) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2570) at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1474) at com.mysql.jdbc.DatabaseMetaData$9.forEach(DatabaseMetaData.java:4967) at com.mysql.jdbc.IterateBlock.doForAll(IterateBlock.java:51) at com.mysql.jdbc.DatabaseMetaData.getTables(DatabaseMetaData.java:4945) at com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnectio nNoQuery(DefaultConnectionTester.java:185) at com.mchange.v2.c3p0.impl.DefaultConnectionTester.activeCheckConnectio n(DefaultConnectionTester.java:62) at com.mchange.v2.c3p0.AbstractConnectionTester.activeCheckConnection(Ab stractConnectionTester.java:67) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionRe sourcePoolManager.testPooledConnection(C3P0PooledConnectionPool.java:368) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionRe sourcePoolManager.refurbishIdleResource(C3P0PooledConnectionPool.java:310) at com.mchange.v2.resourcepool.BasicResourcePool$AsyncTestIdleResourceTa sk.run(BasicResourcePool.java:1999) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(Thre adPoolAsynchronousRunner.java:547) ** END NESTED EXCEPTION ** 以下是连接池配置 jdbc.initialPoolSize = 10 jdbc.minPoolSize = 5 jdbc.maxPoolSize = 30 jdbc.acquireIncrement = 5 jdbc.maxIdleTime = 30 jdbc.maxStatements = 0 jdbc.idleConnectionTestPeriod = 30 jdbc.acquireRetryAttempts = 30 jdbc.breakAfterAcquireFailure = true jdbc.testConnectionOnCheckout = false jdbc.checkoutTimeout = 30000
spring配置方式管理hibernate事务的情况下,每过一段时间产生的错误
项目的背景是struts2+spring+hibernate3 weblogic服务器集群环境 数据库oracle spring管理hibernate 采用配置的方式,配置在了service层。 数据库连接方面使用了hibernate自带的连接池(用其他第三方连接池也试了,问题依旧) 现象:每过一段时间便会报错:(部分) jdbc rollback failed ... TransactionException: JDBC commit failed ... java.sql.SQLRecoverableException: No more data to read from socket ... 错误发生的地方大致在dao层,之中有一个方法,我使用的spring注入的 sessionFactory.getCurrentSession(),然后调用其connection()方法,再使用prepareCall(...)调用存储过程,返回结果。 大致的情况如上。从现象上看像是连接池没有释放的样子,但是我已经在方法最后调用的session.close() rs.close() cstmt.close(); 还是会报错。我猜想是否是因为spring管理事务自动关闭session等和我使用hibernaete的session调用存储过程的方式有什么不协调的地方导致的。请高手帮我提供下思路和解决方案。我没有什么c币和奖分,这个该死的问题已经困扰了我三个星期了,我非常愿意为提供正确产生原因并最终成功解决问题的朋友直接100软妹币的感谢!
java创建一个输出流赋值为null的作用
public class Server { //服务端socket private ServerSocket serverSocket; //所有客户输出流 private List<PrintWriter> allOut; //线程池 private ExecutorService threadPool; /** * 构造方法,用于初始化 * */ public Server() { try{ serverSocket=new ServerSocket(8088); allOut=new ArrayList<PrintWriter>(); threadPool=Executors.newFixedThreadPool(40); }catch(Exception e){ e.printStackTrace(); } } /** * 服务端开启方法 */ public void start(){ while(true){ try{ System.out.println("等待服务端连接!"); //监听客户端连接 Socket socket=serverSocket.accept(); System.out.println("服务端已经连接"); //启动一个线程来完成针对客户端的操作 ClientHandler handler=new ClientHandler(socket); threadPool.execute(handler); }catch(Exception e){ e.printStackTrace(); } } } /** * 将输出流存入共享集合,与下面两个方法互斥 保证同步安全 * @param out */ public synchronized void addOut(PrintWriter out){ allOut.add(out); } /** * 将输出流从共享集合删除 * @param out */ public synchronized void removeOut(PrintWriter out){ allOut.remove(out); } /** * 将信息转发给所有客户端 */ public synchronized void sendMessage(String message){ for(PrintWriter o:allOut){ o.println(message); } } public static void main(String[] args) { Server server=new Server(); server.start(); } /** * 线程体,用于处理不同客户端的交互 * @author Long * */ private class ClientHandler implements Runnable{ private Socket socket; //该线程用于处理客户端 public ClientHandler(Socket socket){ this.socket=socket; } @Override public void run(){ **_PrintWriter writer=null;_** try{ //获取客户端输出流存入共享集合,广播消息 OutputStream os=socket.getOutputStream(); OutputStreamWriter osw=new OutputStreamWriter(os,"utf-8"); writer=new PrintWriter(osw,true); /** * 将用户发的信息存入共享集合,需要同步 */ addOut(writer); InputStream is=socket.getInputStream(); InputStreamReader isr=new InputStreamReader(is, "utf-8"); BufferedReader reader=new BufferedReader(isr); Scanner sc=new Scanner(System.in); String message=null; while((message=reader.readLine())!=null){ sendMessage(message); } }catch(Exception e){ e.printStackTrace(); }finally{ /** * 当客户端断线,要将输出流从共享集合中移除 * 需要同步 */ removeOut(writer); if(socket!=null){ try{ socket.close(); }catch(Exception e){ e.printStackTrace(); } } } } } } 1. 在线程体中(文中黑线)为什么要先PrintWriter writer=null而不是在try中直接赋值
用Mina开发Socket服务器总有一些不可预知的奇怪现象?程序结束不了?!
最近在用 Java的Socket框架mina开发一个服务器端程序,服务器写完后,用mina的客户端API写了程序去连接服务器端,也连接成功了,但是发现每次客户端连接完成运行后 过1分钟客户端程序才结束! 经过调试发现代码已经执行了客户端代码的最后一行! 真是奇怪,客户端代码如下: <br /><pre name="code" class="java">public class Client { private static final String HOSTNAME = "localhost"; private static final int PORT = 20000; public static void main( String[] args ) throws Throwable { SocketConnector connector = new SocketConnector(); // Configure the service. SocketConnectorConfig cfg = new SocketConnectorConfig(); cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) ); cfg.getFilterChain().addLast( "logger", new LoggingFilter() ); IoSession session; try { ConnectFuture future = connector.connect(new InetSocketAddress( HOSTNAME, PORT), new ClientSessionHandler("Hi hi :("), cfg); future.join(); session = future.getSession(); } catch (RuntimeIOException e) { System.err.println("Failed to connect."); e.printStackTrace(); } // wait until the summation is done session.getCloseFuture().join(); System.out.println(session,"### all done! !"); } </pre> <br /> <br />"### all done!  !" 明明都已经打印出来了! 但是发现进程中还是有一个 javaw.exe! 而且用进程管理工具无法结束!,过了1分钟后,这个javaw.exe就没有了,发现eclipse的控制台红色结束按钮也变灰色了. 这些居然都是在最后一行代码执行完发生的? 感觉Java真是一个不稳定的东西~~<img src="/images/smiles/icon_confused.gif" /> <br /><strong>问题补充</strong><br />多谢回复,我看2.0是M版本,好像下载上面写着 unstable,所以没有用,你用这个版本感觉稳定吗?  我刚才又试验了一下 quickServer,试验socket连接到达100个居然就Connnectin refused了? 好像根本没有使用 非阻塞队列. mina虽然有我刚才说的问题,但是他却能坚持到 1000个连接没有发生 Connnectin refused的错误,说明他还是利用了线程池重用了很多连接,我现在马上试试 mina2.0! 我用的是1.1.7,connector没有dispose方法,那个例子我也看到了<br /><strong>问题补充</strong><br />还有你知道他的 httpserver怎么用吗? asyWeb合到mina里面了,我看了例子"httpserver",但是里面居然没有客户端调用示例.客户端怎么传递参数到http服务器也没有说明<br /><strong>问题补充</strong><br />我试了一下2.0M果然可以. 但是服务器端好像不能自己设置连接池了? 下面的代码在2.0不能用,你们怎么用连接池的? 我的性能是要求一台服务器机器需要有1000个并发连接. 我现在服务器这样写不知道有没有问题: <br /><pre name="code" class="java">ExecutorService executor = Executors.newFixedThreadPool(1000); IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.setHandler( new TimeServerHandler() ); acceptor.getSessionConfig().setReadBufferSize( 2048 ); acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 ); acceptor.getFilterChain().addLast("executor", new ExecutorFilter(executor)); acceptor.getFilterChain().addLast( "logger", new LoggingFilter() ); acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) ); acceptor.bind( new InetSocketAddress(PORT) );</pre> <br /> <br />客户端很简单,就是模拟1000个并发连接: <br /><pre name="code" class="java"> public static void main( String[] args ) throws Throwable { for(int i=0;i&lt;1000;i++){ log.info("Enter run l..."+i); new Thread(new ClientThread(i)).start(); } } </pre> <br />每个客户端代码是: <br /><pre name="code" class="java">public void run() { // TODO Auto-generated method stub log.info("#### thread :"+this.num+" Running..."); NioSocketConnector connector = new NioSocketConnector(); // Configure the service. connector.setConnectTimeoutMillis(CONNECT_TIMEOUT); connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) ); connector.getFilterChain().addLast( "logger", new LoggingFilter() ); connector.setHandler(new ClientSessionHandler(" hihi new!")); IoSession session; for (;;) { try { ConnectFuture future = connector.connect(new InetSocketAddress( HOSTNAME, PORT)); future.awaitUninterruptibly(); session = future.getSession(); break; } catch (Exception e) { System.err.println("Failed to connect."); e.printStackTrace(); } } // wait until the summation is done session.getCloseFuture().awaitUninterruptibly(); connector.dispose(); log.info("#### thread :"+this.num+" over ..."); }</pre> <br />不知道这样写是不是已经用了NIO特性和数量是1000的连接池了. 而且我发现客户端如果不用mina的API,直接用Socket API连接,服务器撑不到1000个,200多个就Connection refused了.<br /><strong>问题补充</strong><br />刚才试验了一下,模拟1000个客户端连接,成功了931个,异常是: <br /><pre name="code" class="java">2008-12-28 02:18:06,968 ERROR (LoggingFilter.java:127) - EXCEPTION : java.io.IOException: 您的主机中的软件放弃了一个已建立的连接。 at sun.nio.ch.SocketDispatcher.read0(Native Method) at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:25) at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:233) at sun.nio.ch.IOUtil.read(IOUtil.java:206) at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:207) at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:180) at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:42) at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:568) at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:547) at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:539) at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$400(AbstractPollingIoProcessor.java:57) at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:867) at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:65) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675) at java.lang.Thread.run(Thread.java:595)</pre> <br />不知道调整哪些参数可以不发生这个错误? 就是说调整什么可以使1000个连接都能连上<br /><strong>问题补充</strong><br />windows需要修改OS的一个设置,但是设置了也不起作用,我再试试吧! java的NIO的目的是使服务器端打开尽量少的Socket连接,能处理尽可能多的客户端请求(不知道主要是非阻塞队列起作用还是那个concurrent线程池在发挥作用,应该是前者),这样理解没错吧?
Netty作为socket长链接,在windows部署占用38M左右内存,在linux部署占用1.5G左右内存
不知各位有遇到过这样问题的吗? ![图片说明](https://img-ask.csdn.net/upload/201910/19/1571456018_34605.png) 这是在linux部署直接就这样了 关于启动类我给大家粘一下代码 ``` Thread thread = new Thread(new Runnable() { @Override public void run() { //服务端要建立两个group,一个负责接收客户端的连接,一个负责处理数据传输 //连接处理group EventLoopGroup boss = new NioEventLoopGroup(); //事件处理group EventLoopGroup worker = new NioEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap(); // 绑定处理group bootstrap.group(boss, worker).channel(NioServerSocketChannel.class) //保持连接数 .option(ChannelOption.SO_BACKLOG, 100000) //有数据立即发送 .option(ChannelOption.TCP_NODELAY, true) //保持连接 .childOption(ChannelOption.SO_KEEPALIVE, true) //处理新连接 .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel sc) throws Exception { // 增加任务处理 ChannelPipeline p = sc.pipeline(); p.addLast(new IdleStateHandler(new Integer(new ReadProperties().getUrlValue("read.time.seconds")),0,0)); p.addLast(new ServerIdleStateTrigger()); p.addLast(new Decoder()); p.addLast(new Encoder()); p.addLast(new ServerHandler()); } }).option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT).childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT); //绑定端口,同步等待成功 ChannelFuture future; try { future = bootstrap.bind(serverPort).sync(); if (future.isSuccess()) { serverSocketChannel = (ServerSocketChannel) future.channel(); // System.out.println("服务端开启成功"); // 启动定时删除文件的线程 new Thread(new DeleteFile()).start(); } else { // System.out.println("服务端开启失败"); } //等待服务监听端口关闭,就是由于这里会将线程阻塞,导致无法发送信息,所以我这里开了线程 future.channel().closeFuture().sync(); } catch (Exception e) { // e.printStackTrace(); } finally { //优雅地退出,释放线程池资源 boss.shutdownGracefully(); worker.shutdownGracefully(); } } }); ``` handler类继承SimpleChannelInboundHandler
java与c++通信
我现要做个网站,分2部分。web层和后台服务层,web这块是java来实现,后台服务层是c++。web不能直接访问数据库,要通过c++的一个Serverl来访问(就是web这块只用组合你需要的sql语句,然后发给那个c++端得server,这边在接受他的返回) 现在老大让想想,web和那个c++ server通信的问题,及用户访问量比较大的时候如何处理(并发访问),各位路过的大虾们给小弟指点一下( 小弟积分不多,请各位大侠见谅) 我的想法是要和C++ server通信要用socket 我就在web这块弄个线程连接池,在池中管理这些的线程。启动时开一定数量的线程,当访问量打的时候在建立新的线程,并回收。
请求大佬支援!!!!!! JDBC No value specified for parameter 2
![图片说明](https://img-ask.csdn.net/upload/201906/25/1561436237_114526.png)![图片说明](https://img-ask.csdn.net/upload/201906/25/1561436266_841472.png) ``` package com.sxt.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.Statement; import java.util.Date; /** * 测试PreparedStatement的基本语法 * */ public class Demo3 { public static void main(String[] args) { //加载驱动类 try { Class.forName("com.mysql.cj.jdbc.Driver");//com.mysql.cj.jdbc.Driver mysql6.0以上 //建立连接(连接对象内部起始包含了Socket对象,是一个远程的连接,比较耗时!这是Connection对象管理的一个要点!) //真正开发中,为了提高效率,都会使用连接池来管理连接对象! Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_book?serverTimezone=GMT","root","109867"); System.out.println(conn); String sql = "insert into employees(id,last_name) values (?,?)";//?占位符 PreparedStatement ps = conn.prepareStatement(sql); // ps.setString(1, "qwq");//这里的参数索引是从1开始计算 ps.setString(1, "sa"); // ps.setObject(1,new Date()); System.out.println("插入一行记录"); ps.execute(); } catch (Exception e) { e.printStackTrace(); } } } ```
JedisConnectionException:Could not get a resource
前辈们,您们好: 硬件:win7 64bit webloginc 10.3 (32bit)/java 1.6(安装weblogic使用的自带Java版本) 我使用weblogic部署wap环境后登录(在进入debug之前就会异常),就会出现“不能从连接池获取资源”异常,具体如下: at redis.clients.util.Pool.getResource(Pool.java:22) at com.ai.log.util.redis.RedisManager.getJedis(RedisManager.java:64) at com.ai.log.client.RedisLogAppend.getJedis(RedisLogAppend.java:87) at com.ai.log.client.RedisLogAppend.append(RedisLogAppend.java:48) at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:221) at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:57) at org.apache.log4j.Category.callAppenders(Category.java:187) at org.apache.log4j.Category.forcedLog(Category.java:372) at org.apache.log4j.Category.error(Category.java:286) ……(此处省略更多行) Caused by: redis.clients.jedis.exceptions.JedisConnectionException: java.net.SocketTimeoutException: connect timed out at redis.clients.jedis.Connection.connect(Connection.java:134) at redis.clients.jedis.BinaryClient.connect(BinaryClient.java:69) at redis.clients.jedis.BinaryJedis.connect(BinaryJedis.java:1665) at redis.clients.jedis.JedisPool$JedisFactory.makeObject(JedisPool.java:72) at org.apache.commons.pool.impl.GenericObjectPool.borrowObject(GenericObjectPool.java:840) at redis.clients.util.Pool.getResource(Pool.java:20) ... 79 more Caused by: java.net.SocketTimeoutException: connect timed out at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:339) at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:200) at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:182) at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) at java.net.Socket.connect(Socket.java:579) at redis.clients.jedis.Connection.connect(Connection.java:129) ... 84 more 我使用过的方法:1、更改redis.properties配置(非-1、大数字也试过) MaxActive=-1 MaxIdle=-1 MaxWait=10000 2、试过安装官网通用版weblogic 10.X; 3、考虑更换Tomcat部署,但是配置文件太多(15个),不知道如何部署。 发梢挠到后脑勺,异常坚强如磐石。
java.sql.SQLException: "Too many connections"
org.hibernate.exception.JDBCConnectionException: Cannot open connection OperateDatabase.java queryAll(String hql)查询结果出来啦 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:97) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449) at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1577) at org.hibernate.loader.Loader.doQuery(Loader.java:696) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2232) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129) at org.hibernate.loader.Loader.list(Loader.java:2124) at org.hibernate.loader.custom.CustomLoader.list(CustomLoader.java:312) at org.hibernate.impl.SessionImpl.listCustomQuery(SessionImpl.java:1723) at org.hibernate.impl.AbstractSessionImpl.list(AbstractSessionImpl.java:165) at org.hibernate.impl.SQLQueryImpl.list(SQLQueryImpl.java:175) at hibernate.OperateDatabase.querySql(OperateDatabase.java:128) at socket.Server$1.run(Server.java:225) at java.lang.Thread.run(Unknown Source) Caused by: java.sql.SQLException: Data source rejected establishment of connection, message from server: "Too many connections" at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1018) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2568) at com.mysql.jdbc.Connection.<init>(Connection.java:1485) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446) ... 15 more Exception in thread "Thread-27" java.lang.NullPointerException at socket.Server$1.run(Server.java:226) at java.lang.Thread.run(Unknown Source) ClientThread.java线程睡眠1000毫秒=1秒 ClientThread.java从客户端发来的聊天内容:{"actiontype":"1","receverName":"192.168.0.107","msgType":false,"senderName":"192.168.0.108","chatDate":"2017-03-03 18:21:08"} ClientThread.java动作类型1 Exception in thread "Thread-25" org.hibernate.exception.JDBCConnectionException: Cannot open connection at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:97) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:52) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:449) at org.hibernate.jdbc.ConnectionManager.getConnection(ConnectionManager.java:167) at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1577) at org.hibernate.loader.Loader.doQuery(Loader.java:696) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:259) at org.hibernate.loader.Loader.doList(Loader.java:2232) at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2129) at org.hibernate.loader.Loader.list(Loader.java:2124) at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:401) at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:363) at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:196) at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1149) at org.hibernate.impl.QueryImpl.list(QueryImpl.java:102) at hibernate.OperateDatabase.query(OperateDatabase.java:87) at chat.ClientThread.run(ClientThread.java:111) Caused by: java.sql.SQLException: Data source rejected establishment of connection, message from server: "Too many connections" at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1018) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2568) at com.mysql.jdbc.Connection.<init>(Connection.java:1485) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:266) at java.sql.DriverManager.getConnection(Unknown Source) at java.sql.DriverManager.getConnection(Unknown Source) at org.hibernate.connection.DriverManagerConnectionProvider.getConnection(DriverManagerConnectionProvider.java:133) at org.hibernate.jdbc.ConnectionManager.openConnection(ConnectionManager.java:446) ... 15 more hibernate.hbm.xml文件内容,注释部分是连接池,但貌似使用也不管事 <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- mysql 数据库驱动 --> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <!-- mysql 数据库名 myandroid 端口3306 --> <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myandroid?useUnicode=true&amp;characterEncoding=utf-8</property> <!-- 数据的登录用户名 --> <property name="hibernate.connection.username">root</property> <!-- 数据库的登录秘密 --> <property name="hibernate.connection.password">admin</property> <!-- 下面这一行很重要, 如果hibernate.connection.provider_class没有定义,就会使用内置的连接池,所以如果不想用hibernate内置的连接池,下面这一行必须要写的 --> <!-- <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property> <property name="hibernate.c3p0.max_size">20</property> <property name="hibernate.c3p0.min_size">5</property> <property name="hibernate.c3p0.timeout">120</property> <property name="hibernate.c3p0.max_statements">100</property> <property name="hibernate.c3p0.idle_test_period">120</property> <property name="hibernate.c3p0.acquire_increment">2</property> --> <!-- 方言:为每一种数据库提供适配器,方便转换 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 2,其他配置 --> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 所有的表映射XML文件必须在此录入 导入映射文件--> <mapping resource="hibernate/Customer.hbm.xml"/> <mapping resource="hibernate/ChatLog.hbm.xml"/> <mapping resource="hibernate/ChatMessage.hbm.xml"/> <mapping resource="hibernate/Pitch.hbm.xml"/> </session-factory> </hibernate-configuration>
相见恨晚的超实用网站
相见恨晚的超实用网站 持续更新中。。。
Java学习的正确打开方式
在博主认为,对于入门级学习java的最佳学习方法莫过于视频+博客+书籍+总结,前三者博主将淋漓尽致地挥毫于这篇博客文章中,至于总结在于个人,实际上越到后面你会发现学习的最好方式就是阅读参考官方文档其次就是国内的书籍,博客次之,这又是一个层次了,这里暂时不提后面再谈。博主将为各位入门java保驾护航,各位只管冲鸭!!!上天是公平的,只要不辜负时间,时间自然不会辜负你。 何谓学习?博主所理解的学习,它是一个过程,是一个不断累积、不断沉淀、不断总结、善于传达自己的个人见解以及乐于分享的过程。
程序员必须掌握的核心算法有哪些?
由于我之前一直强调数据结构以及算法学习的重要性,所以就有一些读者经常问我,数据结构与算法应该要学习到哪个程度呢?,说实话,这个问题我不知道要怎么回答你,主要取决于你想学习到哪些程度,不过针对这个问题,我稍微总结一下我学过的算法知识点,以及我觉得值得学习的算法。这些算法与数据结构的学习大多数是零散的,并没有一本把他们全部覆盖的书籍。下面是我觉得值得学习的一些算法以及数据结构,当然,我也会整理一些看过...
有哪些让程序员受益终生的建议
从业五年多,辗转两个大厂,出过书,创过业,从技术小白成长为基层管理,联合几个业内大牛回答下这个问题,希望能帮到大家,记得帮我点赞哦。 敲黑板!!!读了这篇文章,你将知道如何才能进大厂,如何实现财务自由,如何在工作中游刃有余,这篇文章很长,但绝对是精品,记得帮我点赞哦!!!! 一腔肺腑之言,能看进去多少,就看你自己了!!! 目录: 在校生篇: 为什么要尽量进大厂? 如何选择语言及方...
大学四年自学走来,这些私藏的实用工具/学习网站我贡献出来了
大学四年,看课本是不可能一直看课本的了,对于学习,特别是自学,善于搜索网上的一些资源来辅助,还是非常有必要的,下面我就把这几年私藏的各种资源,网站贡献出来给你们。主要有:电子书搜索、实用工具、在线视频学习网站、非视频学习网站、软件下载、面试/求职必备网站。 注意:文中提到的所有资源,文末我都给你整理好了,你们只管拿去,如果觉得不错,转发、分享就是最大的支持了。 一、电子书搜索 对于大部分程序员...
linux系列之常用运维命令整理笔录
本博客记录工作中需要的linux运维命令,大学时候开始接触linux,会一些基本操作,可是都没有整理起来,加上是做开发,不做运维,有些命令忘记了,所以现在整理成博客,当然vi,文件操作等就不介绍了,慢慢积累一些其它拓展的命令,博客不定时更新 free -m 其中:m表示兆,也可以用g,注意都要小写 Men:表示物理内存统计 total:表示物理内存总数(total=used+free) use...
比特币原理详解
一、什么是比特币 比特币是一种电子货币,是一种基于密码学的货币,在2008年11月1日由中本聪发表比特币白皮书,文中提出了一种去中心化的电子记账系统,我们平时的电子现金是银行来记账,因为银行的背后是国家信用。去中心化电子记账系统是参与者共同记账。比特币可以防止主权危机、信用风险。其好处不多做赘述,这一层面介绍的文章很多,本文主要从更深层的技术原理角度进行介绍。 二、问题引入 假设现有4个人...
程序员接私活怎样防止做完了不给钱?
首先跟大家说明一点,我们做 IT 类的外包开发,是非标品开发,所以很有可能在开发过程中会有这样那样的需求修改,而这种需求修改很容易造成扯皮,进而影响到费用支付,甚至出现做完了项目收不到钱的情况。 那么,怎么保证自己的薪酬安全呢? 我们在开工前,一定要做好一些证据方面的准备(也就是“讨薪”的理论依据),这其中最重要的就是需求文档和验收标准。一定要让需求方提供这两个文档资料作为开发的基础。之后开发...
网页实现一个简单的音乐播放器(大佬别看。(⊙﹏⊙))
今天闲着无事,就想写点东西。然后听了下歌,就打算写个播放器。 于是乎用h5 audio的加上js简单的播放器完工了。 演示地点演示 html代码如下` music 这个年纪 七月的风 音乐 ` 然后就是css`*{ margin: 0; padding: 0; text-decoration: none; list-...
Python十大装B语法
Python 是一种代表简单思想的语言,其语法相对简单,很容易上手。不过,如果就此小视 Python 语法的精妙和深邃,那就大错特错了。本文精心筛选了最能展现 Python 语法之精妙的十个知识点,并附上详细的实例代码。如能在实战中融会贯通、灵活使用,必将使代码更为精炼、高效,同时也会极大提升代码B格,使之看上去更老练,读起来更优雅。
数据库优化 - SQL优化
以实际SQL入手,带你一步一步走上SQL优化之路!
2019年11月中国大陆编程语言排行榜
2019年11月2日,我统计了某招聘网站,获得有效程序员招聘数据9万条。针对招聘信息,提取编程语言关键字,并统计如下: 编程语言比例 rank pl_ percentage 1 java 33.62% 2 cpp 16.42% 3 c_sharp 12.82% 4 javascript 12.31% 5 python 7.93% 6 go 7.25% 7 p...
通俗易懂地给女朋友讲:线程池的内部原理
餐盘在灯光的照耀下格外晶莹洁白,女朋友拿起红酒杯轻轻地抿了一小口,对我说:“经常听你说线程池,到底线程池到底是个什么原理?”
《奇巧淫技》系列-python!!每天早上八点自动发送天气预报邮件到QQ邮箱
将代码部署服务器,每日早上定时获取到天气数据,并发送到邮箱。 也可以说是一个小型人工智障。 知识可以运用在不同地方,不一定非是天气预报。
经典算法(5)杨辉三角
杨辉三角 是经典算法,这篇博客对它的算法思想进行了讲解,并有完整的代码实现。
英特尔不为人知的 B 面
从 PC 时代至今,众人只知在 CPU、GPU、XPU、制程、工艺等战场中,英特尔在与同行硬件芯片制造商们的竞争中杀出重围,且在不断的成长进化中,成为全球知名的半导体公司。殊不知,在「刚硬」的背后,英特尔「柔性」的软件早已经做到了全方位的支持与支撑,并持续发挥独特的生态价值,推动产业合作共赢。 而对于这一不知人知的 B 面,很多人将其称之为英特尔隐形的翅膀,虽低调,但是影响力却不容小觑。 那么,在...
腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹?
昨天,有网友私信我,说去阿里面试,彻底的被打击到了。问了为什么网上大量使用ThreadLocal的源码都会加上private static?他被难住了,因为他从来都没有考虑过这个问题。无独有偶,今天笔者又发现有网友吐槽了一道腾讯的面试题,我们一起来看看。 腾讯算法面试题:64匹马8个跑道需要多少轮才能选出最快的四匹? 在互联网职场论坛,一名程序员发帖求助到。二面腾讯,其中一个算法题:64匹...
面试官:你连RESTful都不知道我怎么敢要你?
干货,2019 RESTful最贱实践
刷了几千道算法题,这些我私藏的刷题网站都在这里了!
遥想当年,机缘巧合入了 ACM 的坑,周边巨擘林立,从此过上了"天天被虐似死狗"的生活… 然而我是谁,我可是死狗中的战斗鸡,智力不够那刷题来凑,开始了夜以继日哼哧哼哧刷题的日子,从此"读题与提交齐飞, AC 与 WA 一色 ",我惊喜的发现被题虐既刺激又有快感,那一刻我泪流满面。这么好的事儿作为一个正直的人绝不能自己独享,经过激烈的颅内斗争,我决定把我私藏的十几个 T 的,阿不,十几个刷题网...
SQL-小白最佳入门sql查询一
不要偷偷的查询我的个人资料,即使你再喜欢我,也不要这样,真的不好;
JavaScript 为什么能活到现在?
作者 | 司徒正美 责编 |郭芮 出品 | CSDN(ID:CSDNnews) JavaScript能发展到现在的程度已经经历不少的坎坷,早产带来的某些缺陷是永久性的,因此浏览器才有禁用JavaScript的选项。甚至在jQuery时代有人问出这样的问题,jQuery与JavaScript哪个快?在Babel.js出来之前,发明一门全新的语言代码代替JavaScript...
项目中的if else太多了,该怎么重构?
介绍 最近跟着公司的大佬开发了一款IM系统,类似QQ和微信哈,就是聊天软件。我们有一部分业务逻辑是这样的 if (msgType = "文本") { // dosomething } else if(msgType = "图片") { // doshomething } else if(msgType = "视频") { // doshomething } else { // doshom...
致 Python 初学者
欢迎来到“Python进阶”专栏!来到这里的每一位同学,应该大致上学习了很多 Python 的基础知识,正在努力成长的过程中。在此期间,一定遇到了很多的困惑,对未来的学习方向感到迷茫。我非常理解你们所面临的处境。我从2007年开始接触 python 这门编程语言,从2009年开始单一使用 python 应对所有的开发工作,直至今天。回顾自己的学习过程,也曾经遇到过无数的困难,也曾经迷茫过、困惑过。开办这个专栏,正是为了帮助像我当年一样困惑的 Python 初学者走出困境、快速成长。希望我的经验能真正帮到你
Python 编程开发 实用经验和技巧
Python是一门很灵活的语言,也有很多实用的方法,有时候实现一个功能可以用多种方法实现,我这里总结了一些常用的方法和技巧,包括小数保留指定位小数、判断变量的数据类型、类方法@classmethod、制表符中文对齐、遍历字典、datetime.timedelta的使用等,会持续更新......
吐血推荐珍藏的Visual Studio Code插件
作为一名Java工程师,由于工作需要,最近一个月一直在写NodeJS,这种经历可以说是一部辛酸史了。好在有神器Visual Studio Code陪伴,让我的这段经历没有更加困难。眼看这段经历要告一段落了,今天就来给大家分享一下我常用的一些VSC的插件。 VSC的插件安装方法很简单,只需要点击左侧最下方的插件栏选项,然后就可以搜索你想要的插件了。 下面我们进入正题 Material Theme ...
实战:如何通过python requests库写一个抓取小网站图片的小爬虫
有点爱好的你,偶尔应该会看点图片文字,最近小网站经常崩溃消失,不如想一个办法本地化吧,把小照片珍藏起来! 首先,准备一个珍藏的小网站,然后就可以开始啦! 第一步 我们先写一个获取网站的url的链接,因为url常常是由page或者,其他元素构成,我们就把他分离出来,我找到的网站主页下有图片区 图片区内有标题页,一个标题里有10张照片大概 所以步骤是: 第一步:进入图片区的标题页 def getH...
“狗屁不通文章生成器”登顶GitHub热榜,分分钟写出万字形式主义大作
一、垃圾文字生成器介绍 最近在浏览GitHub的时候,发现了这样一个骨骼清奇的雷人项目,而且热度还特别高。 项目中文名:狗屁不通文章生成器 项目英文名:BullshitGenerator 根据作者的介绍,他是偶尔需要一些中文文字用于GUI开发时测试文本渲染,因此开发了这个废话生成器。但由于生成的废话实在是太过富于哲理,所以最近已经被小伙伴们给玩坏了。 他的文风可能是这样的: 你发现,...
程序员:我终于知道post和get的区别
是一个老生常谈的话题,然而随着不断的学习,对于以前的认识有很多误区,所以还是需要不断地总结的,学而时习之,不亦说乎
《程序人生》系列-这个程序员只用了20行代码就拿了冠军
你知道的越多,你不知道的越多 点赞再看,养成习惯GitHub上已经开源https://github.com/JavaFamily,有一线大厂面试点脑图,欢迎Star和完善 前言 这一期不算《吊打面试官》系列的,所有没前言我直接开始。 絮叨 本来应该是没有这期的,看过我上期的小伙伴应该是知道的嘛,双十一比较忙嘛,要值班又要去帮忙拍摄年会的视频素材,还得搞个程序员一天的Vlog,还要写BU...
加快推动区块链技术和产业创新发展,2019可信区块链峰会在京召开
11月8日,由中国信息通信研究院、中国通信标准化协会、中国互联网协会、可信区块链推进计划联合主办,科技行者协办的2019可信区块链峰会将在北京悠唐皇冠假日酒店开幕。   区块链技术被认为是继蒸汽机、电力、互联网之后,下一代颠覆性的核心技术。如果说蒸汽机释放了人类的生产力,电力解决了人类基本的生活需求,互联网彻底改变了信息传递的方式,区块链作为构造信任的技术有重要的价值。   1...
相关热词 c#委托 逆变与协变 c#新建一个项目 c#获取dll文件路径 c#子窗体调用主窗体事件 c# 拷贝目录 c# 调用cef 网页填表c#源代码 c#部署端口监听项目、 c#接口中的属性使用方法 c# 昨天
立即提问