anderx лет назад: 2
Родитель
Сommit
fe10ecfd42

+ 10 - 10
src/main/java/com/goafanti/baiduAI/bo/OutChatER.java

@@ -1,23 +1,23 @@
 package com.goafanti.baiduAI.bo;
 
 public class OutChatER extends OutSendChat{
-    private Integer errorCode;
-    private String errorMsg;
+    private Integer error_code;
+    private String error_msg;
 
 
-    public Integer getErrorCode() {
-        return errorCode;
+    public Integer getError_code() {
+        return error_code;
     }
 
-    public void setErrorCode(Integer errorCode) {
-        this.errorCode = errorCode;
+    public void setError_code(Integer error_code) {
+        this.error_code = error_code;
     }
 
-    public String getErrorMsg() {
-        return errorMsg;
+    public String getError_msg() {
+        return error_msg;
     }
 
-    public void setErrorMsg(String errorMsg) {
-        this.errorMsg = errorMsg;
+    public void setError_msg(String error_msg) {
+        this.error_msg = error_msg;
     }
 }

+ 4 - 0
src/main/java/com/goafanti/baiduAI/service/BaiduAiService.java

@@ -2,6 +2,9 @@ package com.goafanti.baiduAI.service;
 
 import com.goafanti.baiduAI.bo.InputSendChat;
 import com.goafanti.common.bo.SseEmitterUTF8;
+import com.goafanti.common.model.ErnieBotCommon;
+
+import java.util.List;
 
 public interface BaiduAiService {
 
@@ -9,4 +12,5 @@ public interface BaiduAiService {
     SseEmitterUTF8 sendChat(InputSendChat in);
 
 
+    List<ErnieBotCommon> selectErnieBotCommonAll(Integer count);
 }

+ 12 - 3
src/main/java/com/goafanti/baiduAI/service/impl/BaiduAiServiceImpl.java

@@ -5,13 +5,17 @@ import com.goafanti.baiduAI.BaiduChatErrorEnums;
 import com.goafanti.baiduAI.bo.*;
 import com.goafanti.baiduAI.service.BaiduAiService;
 import com.goafanti.common.bo.SseEmitterUTF8;
+import com.goafanti.common.dao.ErnieBotCommonDao;
 import com.goafanti.common.error.BusinessException;
+import com.goafanti.common.model.ErnieBotCommon;
 import com.goafanti.common.utils.BaiduChatUtils;
 import com.goafanti.common.utils.HttpUtils;
 import com.goafanti.common.utils.LoggerUtils;
 import com.goafanti.common.utils.RedisUtil;
 import com.goafanti.core.shiro.cache.ShiroRedisCache;
 import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.cache.annotation.CacheEvict;
+import org.springframework.cache.annotation.Cacheable;
 import org.springframework.stereotype.Service;
 import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
 
@@ -19,13 +23,15 @@ import javax.annotation.Resource;
 import java.io.IOException;
 import java.util.Calendar;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 
 @Service
 public class BaiduAiServiceImpl implements BaiduAiService {
 
 
-
+    @Autowired
+    private ErnieBotCommonDao ernieBotCommonDao;
 
 
     @Autowired
@@ -47,8 +53,11 @@ public class BaiduAiServiceImpl implements BaiduAiService {
             return sseEmitter;
     }
 
-
-
+    @Override
+    @Cacheable(value = "selectErnieBotCommonAll#300",key = "'page:'+'All'")
+    public List<ErnieBotCommon> selectErnieBotCommonAll(Integer count) {
+        return ernieBotCommonDao.selectAll(count);
+    }
 
 
 }

+ 3 - 2
src/main/java/com/goafanti/common/controller/WebpageController.java

@@ -11,6 +11,7 @@ import java.util.Map;
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 
+import com.goafanti.baiduAI.service.BaiduAiService;
 import com.goafanti.common.dao.ErnieBotCommonDao;
 import com.goafanti.common.model.*;
 import com.goafanti.news.bo.InputJtNews;
@@ -113,7 +114,7 @@ public class WebpageController extends BaseController {
 	private EventPlanningService eventPlanningService;
 
 	@Resource
-	private ErnieBotCommonDao ernieBotCommonDao;
+	private BaiduAiService baiduAiService;
 
 	@RequestMapping(value = "/user/account/index", method = RequestMethod.GET)
 	public ModelAndView index(HttpServletRequest request, ModelAndView modelview) {
@@ -1615,7 +1616,7 @@ public class WebpageController extends BaseController {
 	@RequestMapping("/portal/answers")
 	public ModelAndView answers(ModelAndView modelAndView){
 		modelAndView.setViewName("/portal/answers");
-		List<ErnieBotCommon> list = ernieBotCommonDao.selectAll(6);
+		List<ErnieBotCommon> list = baiduAiService.selectErnieBotCommonAll(6);
 		modelAndView.addObject("list",list);
 		return modelAndView;
 	}

+ 38 - 37
src/main/java/com/goafanti/common/utils/BaiduChatUtils.java

@@ -6,11 +6,13 @@ import com.goafanti.baiduAI.BaiduChatErrorEnums;
 import com.goafanti.baiduAI.bo.*;
 import com.goafanti.common.error.BusinessException;
 import okhttp3.*;
+import org.apache.http.client.ClientProtocolException;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Value;
 import org.springframework.scheduling.annotation.Async;
 import org.springframework.stereotype.Component;
 import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
+import retrofit2.http.GET;
 
 import java.io.BufferedReader;
 import java.io.IOException;
@@ -86,6 +88,8 @@ public class BaiduChatUtils {
 
     @Async
     public void sendBaiduAiStream(InputSendChat inputSendChat) throws IOException {
+        SseResult res = null;
+        BufferedReader reader=null;
         try {
             String baidu_url=BAIDU_CHAT_WXYY_URL+getRedisBaiduAccessToken();
             URL url = new URL(baidu_url);
@@ -101,60 +105,57 @@ public class BaiduChatUtils {
             connection.setRequestProperty("Content-Length", String.valueOf(postData.length));
             connection.getOutputStream().write(postData);
             InputStream responseStream = connection.getInputStream();
-            BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream,"UTF-8"));
+            reader = new BufferedReader(new InputStreamReader(responseStream,"UTF-8"));
             String line;
-            SseResult res =  SseMap.sseEmitterMap.get(inputSendChat.getUserId());
+             res =  SseMap.sseEmitterMap.get(inputSendChat.getUserId());
             while ((line = reader.readLine())!= null) {
                 // 每行数据中以 "data:" 开头的部分即为实际的响应数据
-                System.out.println("relut="+line+"。");
-                if (line.startsWith("data:")) {
-                    String data = line.substring("data:".length()).trim();
-                    JSONObject jsonObject = JSONObject.parseObject(data);
-                    Boolean isEnd = jsonObject.getBoolean("is_end");
-                    if(isEnd){
-                        break;
-                    }
+                if (StringUtils.isNotBlank(line)){
+                    System.out.println(line);
+                    if (line.startsWith("data:")) {
+                        String data = line.substring("data:".length()).trim();
+                        JSONObject jsonObject = JSONObject.parseObject(data);
+                        Boolean isEnd = jsonObject.getBoolean("is_end");
 //                  OutSendChatOK out =jsonObject.toJavaObject(OutSendChatOK.class);
 //                    System.out.println(data);
-                    res.sseEmitter.send(data);
-                }else if(line.startsWith("{")) {
-                    JSONObject jsonObject = JSONObject.parseObject(line);
-                    jsonObject.getString("error_code");
-                    res.sseEmitter.send(line);
+                        res.sseEmitter.send(data);
+                        if(isEnd){
+                            break;
+                        }
+                    }else if(line.startsWith("{")) {
+                        JSONObject jsonObject = JSONObject.parseObject(line);
+                        Integer errorCode = jsonObject.getInteger("error_code");
+                        if (errorCode!=null){
+                            OutChatER out=new OutChatER();
+                            out.setError_code(errorCode);
+                            if (errorCode.equals("336003")){
+                                out.setError_msg(BaiduChatErrorEnums.BycodeGetMsg(errorCode)+jsonObject.getString("error_msg"));
+                            }else {
+                                out.setError_msg(BaiduChatErrorEnums.BycodeGetMsg(errorCode));
+                            }
+                        }
+                        res.sseEmitter.send(JSON.toJSONString(errorCode));
+                    }
                 }
             }
+
             res.sseEmitter.complete();
-            reader.close();
         } catch (MalformedURLException e) {
             e.printStackTrace();
             sendJitaoBaiWen(inputSendChat.getUserId(),"data:{\"error_code\":\"2\",\"error_msg\":\"域名解析异常\"}");
         } catch (ProtocolException e) {
             e.printStackTrace();
-        }
-        SseMap.sseEmitterMap.remove(inputSendChat.getUserId());
-    }
-
-    private OutSendChat pushResultToOutSendChat(String result) {
-
-        Map<String ,Object> resultMap=JSON.parseObject(result, Map.class);
-        Integer errorCode= (Integer) resultMap.get("error_code");
-        if (errorCode!=null){
-            OutChatER res=new OutChatER();
-            res.setErrorCode(errorCode);
-            if (errorCode.equals("336003")){
-                res.setErrorMsg(BaiduChatErrorEnums.BycodeGetMsg(errorCode)+resultMap.get("error_msg"));
-            }else {
-                res.setErrorMsg(BaiduChatErrorEnums.BycodeGetMsg(errorCode));
-            }
-            return res;
-        }else {
-            OutSendChatOK res=new OutSendChatOK();
-            res=JSON.parseObject(result,OutSendChatOK.class);
-            return res;
+        }catch (IllegalStateException e){
+            LoggerUtils.debug(getClass(),"前端网页已关闭");
+        }finally {
+            reader.close();
+            res.sseEmitter.complete();
+            SseMap.sseEmitterMap.remove(inputSendChat.getUserId());
         }
 
     }
 
+
     private void sendJitaoBaiWen(String userId, String s) throws IOException {
         SseResult res =  SseMap.sseEmitterMap.get(userId);
         res.sseEmitter.send(s);

+ 1 - 0
src/main/java/com/goafanti/core/cache/serializer/FastJsonRedisSerializer.java

@@ -24,6 +24,7 @@ public class FastJsonRedisSerializer implements RedisSerializer<Object> {
 		pc.addAccept("com.goafanti.common.model.Activity");
 		pc.addAccept("com.goafanti.portal.bo.InternationalListBo");
 		pc.addAccept("com.goafanti.easemob.bo.EasemobInfo");
+		pc.addAccept("com.goafanti.common.model.ErnieBotCommon");
 	}
 
 	@Override

+ 74 - 0
src/main/java/com/goafanti/core/cache/template/ExtendedRedisCacheManager.java

@@ -0,0 +1,74 @@
+package com.goafanti.core.cache.template;
+
+import com.goafanti.common.utils.LoggerUtils;
+import org.apache.commons.lang3.math.NumberUtils;
+import org.springframework.data.redis.cache.RedisCache;
+import org.springframework.data.redis.cache.RedisCacheManager;
+import org.springframework.data.redis.core.RedisOperations;
+
+import javax.script.ScriptEngine;
+import javax.script.ScriptEngineManager;
+import javax.script.ScriptException;
+import java.util.Objects;
+import java.util.regex.Pattern;
+
+public class ExtendedRedisCacheManager extends RedisCacheManager {
+
+    private static final ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName("JavaScript");
+
+    private static final Pattern pattern = Pattern.compile("[+\\-*/%]");
+
+    /**
+     * 分隔符
+     */
+    private char separator = '#';
+
+    public ExtendedRedisCacheManager(RedisOperations redisOperations) {
+        super(redisOperations);
+    }
+
+
+    @Override
+    @SuppressWarnings("unchecked")
+    protected RedisCache createCache(String cacheName) {
+        // 获取默认时间
+        long expiration = computeExpiration(cacheName);
+        int index = cacheName.indexOf(this.getSeparator());
+        if (index > 0) {
+            expiration = getExpiration(cacheName, index, expiration);
+        }
+        LoggerUtils.debug(this.getClass(),cacheName+",缓存时间="+expiration);
+        return new RedisCache(cacheName, (isUsePrefix() ? getCachePrefix().prefix(cacheName) : null),
+                getRedisOperations(), expiration);
+    }
+
+    /**
+     * 计算缓存时间
+     * @param name 缓存名字 cache#60*60
+     * @param separatorIndex 分隔符位置
+     * @param defalutExp 默认缓存时间
+     * @return
+     */
+    protected long getExpiration(final String name, final int separatorIndex, final long defalutExp) {
+        Long expiration = null;
+        String expirationAsString = name.substring(separatorIndex + 1);
+        try {
+            if (pattern.matcher(expirationAsString).find()) {
+                expiration = NumberUtils.toLong(scriptEngine.eval(expirationAsString).toString(), defalutExp);
+            } else {
+                expiration = NumberUtils.toLong(expirationAsString, defalutExp);
+            }
+        } catch (ScriptException e) {
+            LoggerUtils.fmtError(this.getClass(),e,"缓存时间转换错误:{%s},异常:{%s}",name,e.getMessage());
+        }
+        return Objects.nonNull(expiration) ? expiration.longValue() : defalutExp;
+    }
+
+    public char getSeparator() {
+        return separator;
+    }
+
+    public void setSeparator(char separator) {
+        this.separator = separator;
+    }
+}

+ 10 - 2
src/main/resources/spring/spring-shiro.xml

@@ -47,9 +47,15 @@
 		<constructor-arg index="0" ref="redisConnectionFactory" />
 	</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" />-->
+<!--		<property name="defaultExpiration" value="86400" />-->
+<!--	</bean>-->
+
+	<bean id="cacheManager"
+		  class="com.goafanti.core.cache.template.ExtendedRedisCacheManager">
 		<constructor-arg index="0" ref="redisTemplate" />
-		<property name="defaultExpiration" value="86400" />
+		<property name="defaultExpiration" value="1800" />
 	</bean>
 
 	<bean id="shrioRedisCacheManager" class="com.goafanti.core.shiro.cache.ShiroRedisCacheManager">
@@ -88,6 +94,8 @@
 		<!-- <property name="domain" value=""/> -->
 	</bean>
 
+
+
 	<bean id="customSessionListener" class="com.goafanti.core.shiro.listener.CustomSessionListener">
 		<property name="redisTemplate" ref="sessionRedisTemplate" />
 	</bean>