Przeglądaj źródła

新增技淘百问处理

anderx 2 lat temu
rodzic
commit
70e6112a04

+ 77 - 69
pom.xml

@@ -20,35 +20,35 @@
 		<org.aspectj-version>1.6.10</org.aspectj-version>
 		<org.aspectj-version>1.6.10</org.aspectj-version>
 		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 	</properties>
 	</properties>
-	<profiles>  
-        <profile>  
-            <id>aft_local</id>  
-            <activation>  
-                <activeByDefault>true</activeByDefault>  
-            </activation>  
-            <properties>  
-                <profiles.activation>local</profiles.activation>  
-            </properties>  
-        </profile>  
-        <profile>  
-            <id>aft_dev</id>  
-            <properties>  
-                <profiles.activation>dev</profiles.activation>  
-            </properties>  
-        </profile>  
-        <profile>  
-            <id>aft_prod</id>  
-            <properties>  
-                <profiles.activation>prod</profiles.activation>  
-            </properties>  
-        </profile>  
-        <profile>  
-            <id>aft_test</id>  
-            <properties>  
-                <profiles.activation>test</profiles.activation>  
-            </properties>  
-        </profile>  
-	</profiles> 
+	<profiles>
+        <profile>
+            <id>aft_local</id>
+            <activation>
+                <activeByDefault>true</activeByDefault>
+            </activation>
+            <properties>
+                <profiles.activation>local</profiles.activation>
+            </properties>
+        </profile>
+        <profile>
+            <id>aft_dev</id>
+            <properties>
+                <profiles.activation>dev</profiles.activation>
+            </properties>
+        </profile>
+        <profile>
+            <id>aft_prod</id>
+            <properties>
+                <profiles.activation>prod</profiles.activation>
+            </properties>
+        </profile>
+        <profile>
+            <id>aft_test</id>
+            <properties>
+                <profiles.activation>test</profiles.activation>
+            </properties>
+        </profile>
+	</profiles>
 
 
 	<dependencies>
 	<dependencies>
 		<!-- spring -->
 		<!-- spring -->
@@ -95,13 +95,13 @@
 			<artifactId>spring-messaging</artifactId>
 			<artifactId>spring-messaging</artifactId>
 			<version>${org.springframework-version}</version>
 			<version>${org.springframework-version}</version>
 		</dependency>
 		</dependency>
-		
+
 		<dependency>
 		<dependency>
 		    <groupId>org.springframework.data</groupId>
 		    <groupId>org.springframework.data</groupId>
 		    <artifactId>spring-data-redis</artifactId>
 		    <artifactId>spring-data-redis</artifactId>
 		    <version>1.8.3.RELEASE</version>
 		    <version>1.8.3.RELEASE</version>
 		</dependency>
 		</dependency>
-		
+
 		<dependency>
 		<dependency>
 		    <groupId>org.thymeleaf</groupId>
 		    <groupId>org.thymeleaf</groupId>
 		    <artifactId>thymeleaf-spring4</artifactId>
 		    <artifactId>thymeleaf-spring4</artifactId>
@@ -364,7 +364,7 @@
 			<artifactId>httpasyncclient</artifactId>
 			<artifactId>httpasyncclient</artifactId>
 			<version>4.1.3</version>
 			<version>4.1.3</version>
 		</dependency>
 		</dependency>
-        
+
         <!-- jpush -->
         <!-- jpush -->
 		<dependency>
 		<dependency>
 			<groupId>cn.jpush.api</groupId>
 			<groupId>cn.jpush.api</groupId>
@@ -382,20 +382,28 @@
 			<artifactId>Gson</artifactId>
 			<artifactId>Gson</artifactId>
 			<version>2.5</version>
 			<version>2.5</version>
 		</dependency>
 		</dependency>
-		
+
 		<!-- ffmpeg -->
 		<!-- ffmpeg -->
 		<dependency>
 		<dependency>
 		  <groupId>net.bramp.ffmpeg</groupId>
 		  <groupId>net.bramp.ffmpeg</groupId>
 		  <artifactId>ffmpeg</artifactId>
 		  <artifactId>ffmpeg</artifactId>
 		  <version>0.6.2</version>
 		  <version>0.6.2</version>
 		</dependency>
 		</dependency>
-		
+
 		<!-- commons -->
 		<!-- commons -->
 		<dependency>
 		<dependency>
 		    <groupId>commons-net</groupId>
 		    <groupId>commons-net</groupId>
 		    <artifactId>commons-net</artifactId>
 		    <artifactId>commons-net</artifactId>
 		    <version>3.6</version>
 		    <version>3.6</version>
 		</dependency>
 		</dependency>
+		<!--chatAi输出-->
+		<dependency>
+			<groupId>com.github.plexpt</groupId>
+			<artifactId>chatgpt</artifactId>
+			<version>4.0.7</version>
+		</dependency>
+
+
 	</dependencies>
 	</dependencies>
 	<build>
 	<build>
 		<resources>
 		<resources>
@@ -431,45 +439,45 @@
 					<skip>true</skip>
 					<skip>true</skip>
 				</configuration>
 				</configuration>
 			</plugin>
 			</plugin>
-			<plugin>    
-			    <groupId>org.apache.maven.plugins</groupId>    
-			    <artifactId>maven-surefire-plugin</artifactId>    
-			    <version>2.5</version>    
-			    <configuration>    
-			        <skip>true</skip>    
-			    </configuration>    
-			</plugin> 
-			<plugin>  
-                <groupId>org.apache.maven.plugins</groupId>  
-                <artifactId>maven-war-plugin</artifactId>  
-                <version>3.1.0</version>  
-                <configuration>  
-                    <warName>${profiles.activation}</warName>  
-                    <!-- 激活spring profile -->  
-                    <webResources>  
-                        <resource>  
-                            <filtering>true</filtering>  
-                            <directory>src/main/webapp</directory>  
-                            <includes>  
-                                <include>**/**</include>  
-                            </includes>  
-                        </resource>  
-                        <resource>  
-                            <filtering>true</filtering>  
+			<plugin>
+			    <groupId>org.apache.maven.plugins</groupId>
+			    <artifactId>maven-surefire-plugin</artifactId>
+			    <version>2.5</version>
+			    <configuration>
+			        <skip>true</skip>
+			    </configuration>
+			</plugin>
+			<plugin>
+                <groupId>org.apache.maven.plugins</groupId>
+                <artifactId>maven-war-plugin</artifactId>
+                <version>3.1.0</version>
+                <configuration>
+                    <warName>${profiles.activation}</warName>
+                    <!-- 激活spring profile -->
+                    <webResources>
+                        <resource>
+                            <filtering>true</filtering>
+                            <directory>src/main/webapp</directory>
+                            <includes>
+                                <include>**/**</include>
+                            </includes>
+                        </resource>
+                        <resource>
+                            <filtering>true</filtering>
                             <directory>src/main/resources</directory>
                             <directory>src/main/resources</directory>
                             <targetPath>WEB-INF/classes</targetPath>
                             <targetPath>WEB-INF/classes</targetPath>
-                            <includes>  
-                                <include>**/**</include>  
-                            </includes>  
-                        </resource>  
-                    </webResources>  
-                    <warSourceDirectory>src/main/webapp</warSourceDirectory>  
-                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>  
-                </configuration>  
+                            <includes>
+                                <include>**/**</include>
+                            </includes>
+                        </resource>
+                    </webResources>
+                    <warSourceDirectory>src/main/webapp</warSourceDirectory>
+                    <webXml>src/main/webapp/WEB-INF/web.xml</webXml>
+                </configuration>
 			</plugin>
 			</plugin>
 		</plugins>
 		</plugins>
 	</build>
 	</build>
-	
+
 	<repositories>
 	<repositories>
 		<repository>
 		<repository>
 			<id>aliyun-repos</id>
 			<id>aliyun-repos</id>
@@ -489,4 +497,4 @@
 			</snapshots>
 			</snapshots>
 		</pluginRepository>
 		</pluginRepository>
 	</pluginRepositories>
 	</pluginRepositories>
-</project>
+</project>

+ 53 - 0
src/main/java/com/goafanti/baiduAI/bo/InputSendChat.java

@@ -0,0 +1,53 @@
+package com.goafanti.baiduAI.bo;
+
+import java.util.List;
+
+public class InputSendChat {
+
+    /**
+     * 聊天上下文信息。说明:
+     * (1)messages成员不能为空,1个成员表示单轮对话,多个成员表示多轮对话。
+     * (2)最后一个message为当前请求的信息,前面的message为历史对话信息。
+     * (3)必须为奇数个成员,成员中message的role必须依次为user、assistant。
+     * (4)最后一个message的content长度(即此轮对话的问题)不能超过2000个字符;如果messages中content总长度大于2000字符,系统会依次遗忘最早的历史会话,直到content的总长度不超过2000个字符。
+     */
+    private List<Messages> messages;
+
+    /**
+     * 是否以流式接口的形式返回数据,默认false。
+     */
+    private boolean stream;
+
+    /**
+     * 表示最终用户的唯一标识符,可以监视和检测滥用行为,防止接口恶意调用。
+     */
+    private String userId;
+
+
+    public List<Messages> getMessages() {
+        return messages;
+    }
+
+    public void setMessages(List<Messages> messages) {
+        this.messages = messages;
+    }
+
+    public boolean isStream() {
+        return stream;
+    }
+
+    public void setStream(boolean stream) {
+        this.stream = stream;
+    }
+
+    public String getUserId() {
+        return userId;
+    }
+
+    public void setUserId(String userId) {
+        this.userId = userId;
+    }
+
+
+
+}

+ 38 - 0
src/main/java/com/goafanti/baiduAI/bo/Messages.java

@@ -0,0 +1,38 @@
+package com.goafanti.baiduAI.bo;
+
+public class Messages {
+    /**
+     * 当前支持以下:
+     * user: 表示用户
+     * assistant: 表示对话助手
+     */
+    private String role;
+    /**
+     * 对话内容,不能为空。
+     */
+    private String content;
+
+    public Messages(String role, String content) {
+        this.role = role;
+        this.content = content;
+    }
+
+    public Messages() {
+    }
+
+    public String getRole() {
+        return role;
+    }
+
+    public void setRole(String role) {
+        this.role = role;
+    }
+
+    public String getContent() {
+        return content;
+    }
+
+    public void setContent(String content) {
+        this.content = content;
+    }
+}

+ 4 - 0
src/main/java/com/goafanti/baiduAI/bo/OutSendChat.java

@@ -0,0 +1,4 @@
+package com.goafanti.baiduAI.bo;
+
+public class OutSendChat {
+}

+ 9 - 0
src/main/java/com/goafanti/baiduAI/bo/SseMap.java

@@ -0,0 +1,9 @@
+package com.goafanti.baiduAI.bo;
+
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+
+public class SseMap {
+    public static final Map<String, SseResult> sseEmitterMap = new ConcurrentHashMap<>();
+}

+ 17 - 0
src/main/java/com/goafanti/baiduAI/bo/SseResult.java

@@ -0,0 +1,17 @@
+package com.goafanti.baiduAI.bo;
+
+import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
+
+public class SseResult {
+
+        public String clientId;
+        public long timestamp;
+        public SseEmitter sseEmitter;
+
+        public SseResult(String clientId, long timestamp, SseEmitter sseEmitter) {
+            this.clientId = clientId;
+            this.timestamp = timestamp;
+            this.sseEmitter = sseEmitter;
+        }
+    }
+

+ 64 - 5
src/main/java/com/goafanti/baiduAI/controller/BaiduAiController.java

@@ -1,11 +1,18 @@
 package com.goafanti.baiduAI.controller;
 package com.goafanti.baiduAI.controller;
 
 
+import com.alibaba.fastjson.JSON;
+import com.goafanti.baiduAI.bo.InputSendChat;
+import com.goafanti.baiduAI.bo.OutSendChat;
+import com.goafanti.baiduAI.bo.SseMap;
+import com.goafanti.baiduAI.bo.SseResult;
 import com.goafanti.baiduAI.service.BaiduAiService;
 import com.goafanti.baiduAI.service.BaiduAiService;
 import com.goafanti.common.bo.Result;
 import com.goafanti.common.bo.Result;
+import com.goafanti.common.utils.LoggerUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
+import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
+
+import java.io.IOException;
 
 
 @RestController
 @RestController
 @RequestMapping(value = "/chat")
 @RequestMapping(value = "/chat")
@@ -15,8 +22,60 @@ public class BaiduAiController {
     private BaiduAiService baiduAiService;
     private BaiduAiService baiduAiService;
 
 
     @RequestMapping(value = "/send",method = RequestMethod.POST)
     @RequestMapping(value = "/send",method = RequestMethod.POST)
-    public Result sendChat(String str){
+    public Result sendChat(@RequestBody InputSendChat in){
         Result res =new Result();
         Result res =new Result();
-        return res.data(baiduAiService.sendChat(str));
+        String content = baiduAiService.sendChat(in);
+        OutSendChat outSendChat = JSON.parseObject(content, OutSendChat.class);
+        return res.data(outSendChat);
+    }
+
+
+    @RequestMapping("/start")
+    public SseEmitter testSseEmitter(String clientId) {
+        // 默认30秒超时,设置为0L则永不超时
+        SseEmitter sseEmitter = new SseEmitter(0L);
+        SseMap.sseEmitterMap.put(clientId, new SseResult(clientId, System.currentTimeMillis(), sseEmitter));
+        return sseEmitter;
+    }
+
+
+    /**
+     * 向SseEmitter对象发送数据
+     *
+     * @param clientId
+     * @return
+     */
+    @RequestMapping("/send2")
+    public String setSseEmitter(String clientId) {
+        try {
+            SseResult result =  SseMap.sseEmitterMap.get(clientId);
+            if (result != null && result.sseEmitter != null) {
+                long timestamp = System.currentTimeMillis();
+                String re = "{\"success\":true,\"message\":\"操作成功!\",\"code\":200,\"result\":{\"id\":1018},\"timestamp\":1629254216358}";
+                result.sseEmitter.send(re);
+            }
+        } catch (IOException e) {
+            LoggerUtils.error(getClass(),"IOException");
+            return "error";
+        }
+        return "Succeed!";
+    }
+
+
+    /**
+     * 将SseEmitter对象设置成完成
+     *
+     * @param clientId
+     * @return
+     */
+    @RequestMapping("/end")
+    public String completeSseEmitter(String clientId) {
+        SseResult result =  SseMap.sseEmitterMap.get(clientId);
+        if (result != null) {
+            SseMap.sseEmitterMap.remove(clientId);
+            result.sseEmitter.complete();
+        }
+
+        return "Succeed!";
     }
     }
 }
 }

+ 3 - 1
src/main/java/com/goafanti/baiduAI/service/BaiduAiService.java

@@ -1,7 +1,9 @@
 package com.goafanti.baiduAI.service;
 package com.goafanti.baiduAI.service;
 
 
+import com.goafanti.baiduAI.bo.InputSendChat;
+
 public interface BaiduAiService {
 public interface BaiduAiService {
 
 
 
 
-    String sendChat(String str);
+    String sendChat(InputSendChat in);
 }
 }

+ 13 - 37
src/main/java/com/goafanti/baiduAI/service/impl/BaiduAiServiceImpl.java

@@ -1,66 +1,42 @@
 package com.goafanti.baiduAI.service.impl;
 package com.goafanti.baiduAI.service.impl;
 
 
+import com.goafanti.baiduAI.bo.InputSendChat;
 import com.goafanti.baiduAI.service.BaiduAiService;
 import com.goafanti.baiduAI.service.BaiduAiService;
 import com.goafanti.common.error.BusinessException;
 import com.goafanti.common.error.BusinessException;
 import com.goafanti.common.utils.HttpUtils;
 import com.goafanti.common.utils.HttpUtils;
+import com.goafanti.common.utils.LoggerUtils;
 import com.goafanti.common.utils.RedisUtil;
 import com.goafanti.common.utils.RedisUtil;
+import com.goafanti.core.shiro.cache.ShiroRedisCache;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Service;
 import org.springframework.stereotype.Service;
 
 
+import javax.annotation.Resource;
 import java.io.IOException;
 import java.io.IOException;
 import java.util.Calendar;
 import java.util.Calendar;
 
 
 @Service
 @Service
 public class BaiduAiServiceImpl implements BaiduAiService {
 public class BaiduAiServiceImpl implements BaiduAiService {
 
 
+
+
+
+
     @Autowired
     @Autowired
-    private RedisUtil redisUtil;
+    private HttpUtils httpUtils;
 
 
 
 
     @Override
     @Override
-    public String sendChat(String str) {
-        String redisAccessToken = getRedisAccessToken();
+    public String sendChat(InputSendChat in) {
+
             String result = null;
             String result = null;
         try {
         try {
-            result=HttpUtils.sendBaiduAI(redisAccessToken);
+            result=httpUtils.sendBaiduAI(in);
         } catch (IOException e) {
         } catch (IOException e) {
+            e.printStackTrace();
             throw new BusinessException("文言一心调用失败");
             throw new BusinessException("文言一心调用失败");
         }
         }
         return result;
         return result;
     }
     }
 
 
-    private String  getRedisAccessToken() {
-
-        String redisTime=redisUtil.getString("baiduAccessTime");
-        if (redisTime !=null){
-            Calendar cal = Calendar.getInstance();
-            Long redisAccessTime=Long.valueOf(redisTime);
-            if (cal.getTimeInMillis()>redisAccessTime){
-                redisUtil.deleteString("baiduAccessToken");
-                redisUtil.deleteString("baiduAccessTime");
-            }else {
-                return  redisUtil.getString("baiduAccessToken");
-            }
-        }
-        return getBaiduAccessToken();
-    }
 
 
-    private String getBaiduAccessToken() {
-        String baiduAccessToken;
-        try {
-            baiduAccessToken = HttpUtils.getBaiduAccessToken();
-        } catch (IOException e) {
-            throw new BusinessException("baiduAccessToken获取失败");
-        }
-        //获取当前系统时间
-        Calendar cal = Calendar.getInstance();
-        //将时间增加三十天
-        cal.add(Calendar.DATE, 30);
-        //获取改变后的时间
-        Long baiduAccessTime= cal.getTimeInMillis();
-        redisUtil.setString("baiduAccessToken",baiduAccessToken);
-        redisUtil.setString("baiduAccessTime",baiduAccessTime.toString());
-        return baiduAccessToken;
-    }
 }
 }

+ 75 - 12
src/main/java/com/goafanti/common/utils/HttpUtils.java

@@ -2,6 +2,10 @@ package com.goafanti.common.utils;
 
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSONObject;
 import com.alibaba.fastjson.JSONObject;
+import com.goafanti.baiduAI.bo.InputSendChat;
+import com.goafanti.baiduAI.bo.Messages;
+import com.goafanti.common.error.BusinessException;
+import com.plexpt.chatgpt.listener.SseStreamListener;
 import okhttp3.*;
 import okhttp3.*;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpResponse;
 import org.apache.http.HttpStatus;
 import org.apache.http.HttpStatus;
@@ -14,24 +18,33 @@ import org.apache.http.entity.StringEntity;
 import org.apache.http.impl.client.HttpClientBuilder;
 import org.apache.http.impl.client.HttpClientBuilder;
 import org.apache.http.util.EntityUtils;
 import org.apache.http.util.EntityUtils;
 import org.apache.ibatis.annotations.Param;
 import org.apache.ibatis.annotations.Param;
+import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.beans.factory.annotation.Value;
+import org.springframework.stereotype.Component;
+import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 
 
 import javax.crypto.SecretKey;
 import javax.crypto.SecretKey;
 import java.io.IOException;
 import java.io.IOException;
 import java.nio.charset.Charset;
 import java.nio.charset.Charset;
-import java.util.Map;
+import java.util.*;
+import java.util.concurrent.TimeUnit;
 
 
+@Component
 public class HttpUtils {
 public class HttpUtils {
 
 
+	@Autowired
+	private RedisUtil redisUtil;
 
 
 	@Value(value = "${baidu.ApiKey}")
 	@Value(value = "${baidu.ApiKey}")
-	private static final String baiduApiKey=null;
+	private   String baiduApiKey=null;
 
 
 	@Value(value = "${baidu.SecretKey}")
 	@Value(value = "${baidu.SecretKey}")
-	private static final String baiduSecretKey=null;
+	private   String baiduSecretKey=null;
 
 
 
 
-	static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();
+	static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().connectTimeout(120000, TimeUnit.MILLISECONDS)
+			.readTimeout(120000, TimeUnit.MILLISECONDS)
+			.build();
 
 
 
 
 	 public static JSONObject httpGet(String url) {
 	 public static JSONObject httpGet(String url) {
@@ -133,11 +146,11 @@ public class HttpUtils {
 
 
 
 
 
 
-	public static String  getBaiduAccessToken() throws IOException {
+	public  String  getBaiduAccessToken() throws IOException {
 				MediaType mediaType = MediaType.parse("application/json");
 				MediaType mediaType = MediaType.parse("application/json");
 				RequestBody body = RequestBody.create(mediaType, "");
 				RequestBody body = RequestBody.create(mediaType, "");
-				StringBuffer url= new StringBuffer("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=")
-					.append(baiduApiKey).append("&client_secret=").append(baiduSecretKey);
+				StringBuffer url= new StringBuffer("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&")
+					.append("client_id=").append(baiduApiKey).append("&client_secret=").append(baiduSecretKey);
 				Request request = new Request.Builder()
 				Request request = new Request.Builder()
 						.url(url.toString())
 						.url(url.toString())
 						.method("POST", body)
 						.method("POST", body)
@@ -146,13 +159,16 @@ public class HttpUtils {
 						.build();
 						.build();
 				Response response = HTTP_CLIENT.newCall(request).execute();
 				Response response = HTTP_CLIENT.newCall(request).execute();
 				String result=response.body().string();
 				String result=response.body().string();
-				System.out.println(result);
-				return result;
+		HashMap<String,Object> map = JSON.parseObject(result, HashMap.class);
+		String  accessToken = map.get("access_token").toString();
+		LoggerUtils.debug(getClass(),"获取accessToken="+accessToken);
+		return accessToken;
 	}
 	}
 
 
-	public static String sendBaiduAI(String accessToken) throws IOException{
+	public  String sendBaiduAI(InputSendChat in) throws IOException{
+		String accessToken = getRedisBaiduAccessToken();
 		MediaType mediaType = MediaType.parse("application/json");
 		MediaType mediaType = MediaType.parse("application/json");
-		RequestBody body = RequestBody.create(mediaType, "");
+		RequestBody body = RequestBody.create(mediaType, JSON.toJSONString(in));
 		Request request = new Request.Builder()
 		Request request = new Request.Builder()
 				.url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + accessToken)
 				.url("https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + accessToken)
 				.method("POST", body)
 				.method("POST", body)
@@ -160,9 +176,56 @@ public class HttpUtils {
 				.build();
 				.build();
 		Response response = HTTP_CLIENT.newCall(request).execute();
 		Response response = HTTP_CLIENT.newCall(request).execute();
 		String result=response.body().string();
 		String result=response.body().string();
-		System.out.println(result);
+		SseEmitter sseEmitter=new SseEmitter(0l);
+		SseStreamListener listener=new SseStreamListener(sseEmitter);
+
+
 		return result;
 		return result;
 	}
 	}
 
 
 
 
+
+
+
+	private String  getRedisBaiduAccessToken() {
+		String redisAccessToken=null;
+		String redisTime=redisUtil.getString("baiduAccessTime");
+		//没有
+		if (redisTime !=null){
+			Calendar cal = Calendar.getInstance();
+			Long redisAccessTime=Long.valueOf(redisTime);
+			if (cal.getTimeInMillis()>redisAccessTime){
+				redisUtil.deleteString("baiduAccessToken");
+				redisUtil.deleteString("baiduAccessTime");
+				redisAccessToken=pushRedisBaiduAccessToken();
+				LoggerUtils.debug(getClass(),"accessToken过期,重新获取");
+			}else {
+				redisAccessToken=  redisUtil.getString("baiduAccessToken");
+				LoggerUtils.debug(getClass(),"accessToken从redis获取");
+			}
+		}else {
+			redisAccessToken=pushRedisBaiduAccessToken();
+			LoggerUtils.debug(getClass(),"accessToken不存在,从百度获取");
+		}
+		return redisAccessToken;
+	}
+
+	private String pushRedisBaiduAccessToken() {
+		String baiduAccessToken;
+		try {
+			baiduAccessToken = getBaiduAccessToken();
+		} catch (IOException e) {
+			throw new BusinessException("baiduAccessToken获取失败");
+		}
+		//获取当前系统时间
+		Calendar cal = Calendar.getInstance();
+		//将时间增加三十天
+		cal.add(Calendar.DATE, 30);
+		//获取改变后的时间
+		Long baiduAccessTime= cal.getTimeInMillis();
+        redisUtil.setString("baiduAccessToken",baiduAccessToken);
+        redisUtil.setString("baiduAccessTime",baiduAccessTime.toString());
+		return baiduAccessToken;
+	}
+
 }
 }

+ 6 - 6
src/main/java/com/goafanti/common/utils/PasswordUtil.java

@@ -11,7 +11,7 @@ import com.goafanti.common.model.SkjtUser;
 import com.goafanti.common.model.User;
 import com.goafanti.common.model.User;
 
 
 public class PasswordUtil {
 public class PasswordUtil {
-	private String algorithmName = "md5";
+	private String algorithmName = null;
 	private int hashIterations = 2;
 	private int hashIterations = 2;
 
 
 	public void setAlgorithmName(String algorithmName) {
 	public void setAlgorithmName(String algorithmName) {
@@ -25,7 +25,7 @@ public class PasswordUtil {
 	public void encryptPassword(User user) {
 	public void encryptPassword(User user) {
 		user.setPassword(getEncryptPwd(user));
 		user.setPassword(getEncryptPwd(user));
 	}
 	}
-	
+
 	public void encryptPassword(Admin admin){
 	public void encryptPassword(Admin admin){
 		admin.setPassword(getEncryptPwd(admin));
 		admin.setPassword(getEncryptPwd(admin));
 	}
 	}
@@ -33,11 +33,11 @@ public class PasswordUtil {
 	public String getEncryptPwd(User user) {
 	public String getEncryptPwd(User user) {
 		return new SimpleHash(algorithmName, user.getPassword(), getSalt(user), hashIterations).toHex();
 		return new SimpleHash(algorithmName, user.getPassword(), getSalt(user), hashIterations).toHex();
 	}
 	}
-	
+
 	public String getEncryptPwd(SkjtUser user) {
 	public String getEncryptPwd(SkjtUser user) {
 		return new SimpleHash(algorithmName, user.getPassword(), getSkjtSalt(user), hashIterations).toHex();
 		return new SimpleHash(algorithmName, user.getPassword(), getSkjtSalt(user), hashIterations).toHex();
 	}
 	}
-	
+
 	public String getEncryptPwd(Admin admin) {
 	public String getEncryptPwd(Admin admin) {
 		return new SimpleHash(algorithmName, admin.getPassword(), getManageSalt(admin), hashIterations).toHex();
 		return new SimpleHash(algorithmName, admin.getPassword(), getManageSalt(admin), hashIterations).toHex();
 	}
 	}
@@ -49,14 +49,14 @@ public class PasswordUtil {
 	public ByteSource getSalt(User user) {
 	public ByteSource getSalt(User user) {
 		return ByteSource.Util.bytes(String.valueOf(user.getCreateTime().getTime()));
 		return ByteSource.Util.bytes(String.valueOf(user.getCreateTime().getTime()));
 	}
 	}
-	
+
 	public ByteSource getManageSalt(Admin admin) {
 	public ByteSource getManageSalt(Admin admin) {
 		return ByteSource.Util.bytes(String.valueOf(admin.getCreateTime().getTime()));
 		return ByteSource.Util.bytes(String.valueOf(admin.getCreateTime().getTime()));
 	}
 	}
 	public ByteSource getSkjtSalt(SkjtUser user) {
 	public ByteSource getSkjtSalt(SkjtUser user) {
 		return ByteSource.Util.bytes(String.valueOf(user.getCreateTime().getTime()));
 		return ByteSource.Util.bytes(String.valueOf(user.getCreateTime().getTime()));
 	}
 	}
-	
+
 	public ByteSource getAftSalt(AftUser aftUser) {
 	public ByteSource getAftSalt(AftUser aftUser) {
 		return ByteSource.Util.bytes(String.valueOf(aftUser.getCreateTime().getTime()));
 		return ByteSource.Util.bytes(String.valueOf(aftUser.getCreateTime().getTime()));
 	}
 	}

+ 2 - 6
src/main/java/com/goafanti/common/utils/RedisUtil.java

@@ -3,7 +3,6 @@ package com.goafanti.common.utils;
 
 
 import com.alibaba.fastjson.JSON;
 import com.alibaba.fastjson.JSON;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
 import org.springframework.stereotype.Component;
 import org.springframework.stereotype.Component;
 import redis.clients.jedis.Jedis;
 import redis.clients.jedis.Jedis;
 import redis.clients.jedis.JedisPool;
 import redis.clients.jedis.JedisPool;
@@ -19,10 +18,7 @@ import java.util.Set;
  */
  */
 @Component
 @Component
 public class RedisUtil {
 public class RedisUtil {
-	@Value(value = "${jedis.host}")
-	private  String host;
-	@Value(value = "${jedis.password}")
-	private  String pwd;
+
 	@Autowired
 	@Autowired
 	private  JedisPool pool;//创建代理对象
 	private  JedisPool pool;//创建代理对象
 
 
@@ -60,7 +56,7 @@ public class RedisUtil {
 
 
 
 
 
 
-	public boolean presence(String key){
+	public  boolean presence(String key){
 		Jedis jedis = pool.getResource();
 		Jedis jedis = pool.getResource();
 		boolean bool=true;
 		boolean bool=true;
 		try {
 		try {

+ 26 - 23
src/main/resources/spring/spring-mvc.xml

@@ -3,32 +3,35 @@
 	xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
 	xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
 	xmlns:context="http://www.springframework.org/schema/context"
 	xmlns:context="http://www.springframework.org/schema/context"
-	xsi:schemaLocation="http://www.springframework.org/schema/beans 
-	http://www.springframework.org/schema/beans/spring-beans.xsd 
-	http://www.springframework.org/schema/context 
-	http://www.springframework.org/schema/context/spring-context-4.0.xsd 
+	xsi:schemaLocation="http://www.springframework.org/schema/beans
+	http://www.springframework.org/schema/beans/spring-beans.xsd
+	http://www.springframework.org/schema/context
+	http://www.springframework.org/schema/context/spring-context-4.0.xsd
 	http://www.springframework.org/schema/task
 	http://www.springframework.org/schema/task
 	http://www.springframework.org/schema/task/spring-task-4.0.xsd
 	http://www.springframework.org/schema/task/spring-task-4.0.xsd
-	http://www.springframework.org/schema/mvc 
+	http://www.springframework.org/schema/mvc
 	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 
 
 	<!-- Scan controller -->
 	<!-- Scan controller -->
-		
+
 	<context:component-scan
 	<context:component-scan
-		base-package="com.goafanti.*.controller;com.goafanti.*.*.controller;com.goafanti.common.task;com.goafanti.core.websocket" />
+		base-package="com.goafanti.*.controller;com.goafanti.common.task;com.goafanti.core.websocket" />
 
 
 	<bean name="springContextUtils" class="com.goafanti.common.utils.SpringContextUtils" scope="singleton"></bean>
 	<bean name="springContextUtils" class="com.goafanti.common.utils.SpringContextUtils" scope="singleton"></bean>
-	
+
 	<bean id="passwordUtil" class="com.goafanti.common.utils.PasswordUtil">
 	<bean id="passwordUtil" class="com.goafanti.common.utils.PasswordUtil">
-		<property name="algorithmName" value="${pwd.hash_algorithm_name}"/>  
-	    <property name="hashIterations" value="${pwd.hash_iterations}"/> 
+		<property name="algorithmName" value="${pwd.hash_algorithm_name}"/>
+	    <property name="hashIterations" value="${pwd.hash_iterations}"/>
+	</bean>
+	<bean id="redisUtils" class="com.goafanti.common.utils.RedisUtil">
+
 	</bean>
 	</bean>
-	
+
 	<!-- spring bean validator -->
 	<!-- spring bean validator -->
-	
+
 <!-- 配置注解驱动 -->
 <!-- 配置注解驱动 -->
 	<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
 	<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
-	
+
 	<!-- 校验器 -->
 	<!-- 校验器 -->
 	<bean id="validator"
 	<bean id="validator"
 		class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
 		class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
@@ -36,8 +39,8 @@
 		<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
 		<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
 		<!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties -->
 		<!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下的ValidationMessages.properties -->
 		<property name="validationMessageSource" ref="messageSource" />
 		<property name="validationMessageSource" ref="messageSource" />
-	</bean>	
-	
+	</bean>
+
 	<!-- 校验错误信息配置文件 -->
 	<!-- 校验错误信息配置文件 -->
 	<bean id="messageSource"
 	<bean id="messageSource"
 		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
 		class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
@@ -50,15 +53,15 @@
 	</bean>
 	</bean>
 
 
 
 
-	<!-- Handles HTTP GET requests for /assets/** by efficiently serving up 
+	<!-- Handles HTTP GET requests for /assets/** by efficiently serving up
 		static resources in the ${webappRoot}/assets directory -->
 		static resources in the ${webappRoot}/assets directory -->
 	<mvc:resources mapping="/static/images/**" location="/WEB-INF/images/" />
 	<mvc:resources mapping="/static/images/**" location="/WEB-INF/images/" />
 	<mvc:resources mapping="/static/html/**" location="/WEB-INF/html/" />
 	<mvc:resources mapping="/static/html/**" location="/WEB-INF/html/" />
 	<mvc:resources mapping="/static/**" location="/WEB-INF/build/" />
 	<mvc:resources mapping="/static/**" location="/WEB-INF/build/" />
 	<mvc:resources mapping="/favicon.ico" location="/WEB-INF/assets/favicon.ico" />
 	<mvc:resources mapping="/favicon.ico" location="/WEB-INF/assets/favicon.ico" />
 	<mvc:resources mapping="/robots.txt" location="/WEB-INF/assets/robots.txt" />
 	<mvc:resources mapping="/robots.txt" location="/WEB-INF/assets/robots.txt" />
-	
-	<bean id="templateResolver" 
+
+	<bean id="templateResolver"
         class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
         class="org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver">
         <property name="prefix" value="/WEB-INF/views/" />
         <property name="prefix" value="/WEB-INF/views/" />
         <property name="suffix" value=".html" />
         <property name="suffix" value=".html" />
@@ -71,13 +74,13 @@
     <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
     <bean id="templateEngine" class="org.thymeleaf.spring4.SpringTemplateEngine">
         <property name="templateResolver" ref="templateResolver" />
         <property name="templateResolver" ref="templateResolver" />
     </bean>
     </bean>
-    
+
     <!-- Simple strategy: only path extension is taken into account -->
     <!-- Simple strategy: only path extension is taken into account -->
     <bean id="cnManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
     <bean id="cnManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
         <property name="favorPathExtension" value="true"/>
         <property name="favorPathExtension" value="true"/>
         <property name="ignoreAcceptHeader" value="true"/>
         <property name="ignoreAcceptHeader" value="true"/>
         <property name="defaultContentType" value="text/html"/>
         <property name="defaultContentType" value="text/html"/>
-        
+
         <property name="mediaTypes">
         <property name="mediaTypes">
             <map>
             <map>
                 <entry key="html" value="text/html" />
                 <entry key="html" value="text/html" />
@@ -86,7 +89,7 @@
             </map>
             </map>
         </property>
         </property>
     </bean>
     </bean>
-    
+
     <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
     <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
         <property name="contentNegotiationManager" ref="cnManager"/>
         <property name="contentNegotiationManager" ref="cnManager"/>
         <property name="viewResolvers">
         <property name="viewResolvers">
@@ -143,5 +146,5 @@
 		<property name="appName" value="${app.name}" />
 		<property name="appName" value="${app.name}" />
 	</bean>
 	</bean>
 	<bean id="systemWebSocketHandler" class="com.goafanti.core.websocket.SystemWebSocketHandler" scope="singleton"></bean>
 	<bean id="systemWebSocketHandler" class="com.goafanti.core.websocket.SystemWebSocketHandler" scope="singleton"></bean>
-	
-</beans>
+
+</beans>

+ 34 - 18
src/main/resources/spring/spring-shiro.xml

@@ -15,6 +15,20 @@
 		<property name="minIdle" value="10" />
 		<property name="minIdle" value="10" />
 		<property name="testOnBorrow" value="true" />
 		<property name="testOnBorrow" value="true" />
 	</bean>
 	</bean>
+	<bean id="poolConfig" class="org.apache.commons.pool2.impl.GenericObjectPoolConfig">
+		<property name="minIdle" value="5"/>
+		<property name="maxIdle" value="20"/>
+		<property name="maxWaitMillis" value="100000"/>
+		<property name="maxTotal" value="10000"/>
+	</bean>
+
+	<bean id="jedisPool" class="redis.clients.jedis.JedisPool">
+		<constructor-arg name="poolConfig" ref="poolConfig"/>
+		<constructor-arg name="host" value="${jedis.host}"/>
+		<constructor-arg name="port" value="${jedis.port}"/>
+		<constructor-arg name="password" value="${jedis.password}"/>
+		<constructor-arg name="timeout" value="1000000"/>
+	</bean>
 
 
 	<bean id="redisConnectionFactory"
 	<bean id="redisConnectionFactory"
 		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
 		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
@@ -32,33 +46,35 @@
 	<bean id="sessionRedisTemplate" class="com.goafanti.core.shiro.cache.template.SessionRedisTemplate">
 	<bean id="sessionRedisTemplate" class="com.goafanti.core.shiro.cache.template.SessionRedisTemplate">
 		<constructor-arg index="0" ref="redisConnectionFactory" />
 		<constructor-arg index="0" ref="redisConnectionFactory" />
 	</bean>
 	</bean>
-	
+
 	<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
 	<bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager">
 		<constructor-arg index="0" ref="redisTemplate" />
 		<constructor-arg index="0" ref="redisTemplate" />
-		<property name="defaultExpiration" value="86400" />		
+		<property name="defaultExpiration" value="86400" />
 	</bean>
 	</bean>
-	
+
 	<bean id="shrioRedisCacheManager" class="com.goafanti.core.shiro.cache.ShiroRedisCacheManager">
 	<bean id="shrioRedisCacheManager" class="com.goafanti.core.shiro.cache.ShiroRedisCacheManager">
 		<property name="redisTemplate" ref="sessionRedisTemplate" />
 		<property name="redisTemplate" ref="sessionRedisTemplate" />
 		<property name="expire" value="2592000" />
 		<property name="expire" value="2592000" />
 	</bean>
 	</bean>
-	
+
 	<!-- 环信 -->
 	<!-- 环信 -->
-    <bean id="jedisQueueListener" class="com.goafanti.easemob.queue.EasemobRedisQueueListener"/>  
-    <bean id="jedisQueue" class="com.goafanti.easemob.queue.EasemobRedisQueue" destroy-method="destroy">  
-        <property name="redisTemplate" ref="redisTemplate"></property>  
-        <property name="key" value="easemob:queue"></property>  
-        <property name="listener" ref="jedisQueueListener"></property>  
-    </bean> 
+    <bean id="jedisQueueListener" class="com.goafanti.easemob.queue.EasemobRedisQueueListener"/>
+    <bean id="jedisQueue" class="com.goafanti.easemob.queue.EasemobRedisQueue" destroy-method="destroy">
+        <property name="redisTemplate" ref="redisTemplate"></property>
+        <property name="key" value="easemob:queue"></property>
+        <property name="listener" ref="jedisQueueListener"></property>
+    </bean>
+	<bean id="HttpUtils" class="com.goafanti.common.utils.HttpUtils"/>
     <bean id="easemobUtils" class="com.goafanti.easemob.EasemobUtils"/>
     <bean id="easemobUtils" class="com.goafanti.easemob.EasemobUtils"/>
-      
+
+
 	<!-- 极光 -->
 	<!-- 极光 -->
-    <bean id="messageQueueListener" class="com.goafanti.message.queue.MessageRedisQueueListener"/>  
-    <bean id="messageQueue" class="com.goafanti.message.queue.MessageRedisQueue" destroy-method="destroy">  
-        <property name="redisTemplate" ref="redisTemplate"></property>  
-        <property name="key" value="jgpush:queue"></property>  
-        <property name="listener" ref="messageQueueListener"></property>  
-    </bean> 
+    <bean id="messageQueueListener" class="com.goafanti.message.queue.MessageRedisQueueListener"/>
+    <bean id="messageQueue" class="com.goafanti.message.queue.MessageRedisQueue" destroy-method="destroy">
+        <property name="redisTemplate" ref="redisTemplate"></property>
+        <property name="key" value="jgpush:queue"></property>
+        <property name="listener" ref="messageQueueListener"></property>
+    </bean>
     <bean id="jgMessageHelper" class="com.goafanti.message.JGMessageHelper"/>
     <bean id="jgMessageHelper" class="com.goafanti.message.JGMessageHelper"/>
 
 
 	<bean id="sessionIdGenerator"
 	<bean id="sessionIdGenerator"
@@ -168,4 +184,4 @@
 	</bean>
 	</bean>
 	<!-- -->
 	<!-- -->
 	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
 	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
-</beans>
+</beans>