Jelajahi Sumber

1.存redis 处理 qlm

qlm 4 tahun lalu
induk
melakukan
efc4f67f7c

+ 16 - 10
pom.xml

@@ -208,16 +208,22 @@
 
         <!-- redis -->
         <!-- Spring Boot Redis 依赖 -->
-        <dependency>
-            <groupId>org.springframework.boot</groupId>
-            <artifactId>spring-boot-starter-data-redis</artifactId>
-            <exclusions>
-                <exclusion>
-                    <groupId>io.lettuce</groupId>
-                    <artifactId>lettuce-core</artifactId>
-                </exclusion>
-            </exclusions>
-        </dependency>
+        <!--<dependency>-->
+            <!--<groupId>org.springframework.boot</groupId>-->
+            <!--<artifactId>spring-boot-starter-data-redis</artifactId>-->
+            <!--<exclusions>-->
+                <!--<exclusion>-->
+                    <!--<groupId>io.lettuce</groupId>-->
+                    <!--<artifactId>lettuce-core</artifactId>-->
+                <!--</exclusion>-->
+            <!--</exclusions>-->
+        <!--</dependency>-->
+        <dependency>
+        <groupId>org.springframework.session</groupId>
+        <artifactId>spring-session-data-redis</artifactId>
+        <version>1.2.0.RELEASE</version>
+    </dependency>
+
         <dependency>
             <groupId>redis.clients</groupId>
             <artifactId>jedis</artifactId>

+ 5 - 0
src/main/java/com/zx/dataservice/config/JfinalActiveRecordConfig.java

@@ -167,6 +167,11 @@ public class JfinalActiveRecordConfig implements ApplicationRunner {
             WSOptions.set(record.getStr("wskey"),record.getStr("wsname")+"_"+record.getStr("wsvalue"));
         }
         ActiveConfig.activeRisk();
+        for (int i = 0; i < 5; i++) {
+            Thread.sleep(1000);
+        }
+        ZXOptions.set("run","true");
+
     }
 
     @PreDestroy

+ 40 - 1
src/main/java/com/zx/dataservice/controller/CallBackController.java

@@ -1,11 +1,16 @@
 package com.zx.dataservice.controller;
 
+import com.alibaba.fastjson.JSON;
+import com.alibaba.fastjson.JSONArray;
 import com.jfinal.plugin.activerecord.Db;
 import com.jfinal.plugin.activerecord.Record;
 import com.zx.dataservice.config.ActiveConfig;
 import com.zx.dataservice.options.WSOptions;
 import com.zx.dataservice.options.ZXOptions;
+import com.zx.dataservice.redismessage.util.RedisUtil;
 import com.zx.dataservice.service.ChoiceHisService;
+import com.zx.dataservice.vo.StockVO;
+import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -14,6 +19,8 @@ import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.ResponseBody;
 
+import java.util.ArrayList;
+import java.util.Iterator;
 import java.util.List;
 
 @Controller
@@ -153,8 +160,40 @@ public class CallBackController {
         }
         return s;
     }
+    @Autowired
+    private RedisUtil redisUtil;
 
-
+    @RequestMapping({"showRedis.do"})
+    @ResponseBody
+    public String showRedis(String key, String code) {
+        String redisData = "";
+        try {
+            if (StringUtils.isBlank(key)) {
+                key = "data_stock";
+            }
+            String redisKey = String.format(key);
+            redisData = redisUtil.getItem(redisKey);
+            if (StringUtils.isNotBlank(code)) {
+                List<StockVO> stockRedisList = new ArrayList<>();
+                if (StringUtils.isNotEmpty(redisData) && !("[]".equals(redisData))) {
+                    stockRedisList = JSONArray.parseArray(redisData, StockVO.class);
+                    Iterator<StockVO> iteratorRedis = stockRedisList.iterator();
+                    while (iteratorRedis.hasNext()) {
+                        StockVO stockRedis = iteratorRedis.next();
+                        if (code.equals(stockRedis.getCode())) {
+                            redisData = JSON.toJSONString(stockRedis);
+                            break;
+                        }
+                    }
+                }
+            }
+        } catch (Exception e) {
+            e.printStackTrace();
+            return e.toString();
+        }
+        new WebSocketController().sendSysMsg("hydata201226",redisData);
+        return redisData;
+    }
 
 
 

+ 18 - 3
src/main/java/com/zx/dataservice/controller/WebSocketController.java

@@ -205,8 +205,16 @@ public class WebSocketController {
                         // 推送对应的 风控 记录
                         synchronized(session){
                             if(session.isOpen()){
-                                List<StockRestRedisVO> stockRestRedisVOS = mapws.get("stockRestRedisVO_" + WSOptions.get(key).split("_")[0]);
-                                session.getBasicRemote().sendText(JSON.toJSONString(stockRestRedisVOS));
+                                String time1 = "14:59:00";
+                                String time2 = "16:00:00";
+                                if(Integer.parseInt(DateUtils.parseDateToStr("ss",new Date()))%5==0
+                                        ||Integer.parseInt(DateUtils.parseDateToStr("ss",new Date()))%6==0
+                                        ||((DateUtils.formatToDate(time1).before(DateUtils.formatToDate(DateUtils.getHhMmSs())))
+                                        &&(DateUtils.formatToDate(DateUtils.getHhMmSs()).before(DateUtils.formatToDate(time2))))){
+                                    List<StockRestRedisVO> stockRestRedisVOS = mapws.get("stockRestRedisVO_" + WSOptions.get(key).split("_")[0]);
+                                    session.getBasicRemote().sendText(JSON.toJSONString(stockRestRedisVOS));
+                                }
+
                             }
                         }
                     }
@@ -246,7 +254,14 @@ public class WebSocketController {
                         // 推送对应的 风控 记录
                         synchronized(session){
                             if(session.isOpen()){
-                                session.getBasicRemote().sendText(xMessage);
+                                String time1 = "14:59:00";
+                                String time2 = "16:00:00";
+                                if(Integer.parseInt(DateUtils.parseDateToStr("ss",new Date()))%5==0
+                                        ||Integer.parseInt(DateUtils.parseDateToStr("ss",new Date()))%6==0
+                                        ||((DateUtils.formatToDate(time1).before(DateUtils.formatToDate(DateUtils.getHhMmSs())))
+                                            &&(DateUtils.formatToDate(DateUtils.getHhMmSs()).before(DateUtils.formatToDate(time2))))){
+                                    session.getBasicRemote().sendText(xMessage);
+                                }
                             }
                         }
                     }

+ 72 - 0
src/main/java/com/zx/dataservice/redismessage/conf/RedisConfig.java

@@ -0,0 +1,72 @@
+package com.zx.dataservice.redismessage.conf;
+
+import com.fasterxml.jackson.annotation.JsonAutoDetect;
+import com.fasterxml.jackson.annotation.PropertyAccessor;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.zx.dataservice.redismessage.listener.RedisMessageListener;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.Bean;
+import org.springframework.context.annotation.Configuration;
+import org.springframework.data.redis.connection.RedisConnectionFactory;
+import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.StringRedisTemplate;
+import org.springframework.data.redis.listener.PatternTopic;
+import org.springframework.data.redis.listener.RedisMessageListenerContainer;
+import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
+
+
+@Configuration
+public class RedisConfig {
+
+    @Value("channel01")
+    private String channelName;
+
+
+    /**
+     * redis 数据库连接池
+     *
+     * @return
+     */
+    @Bean
+    public JedisConnectionFactory redisConnectionFactory() {
+        JedisConnectionFactory factory = new JedisConnectionFactory();
+        factory.setHostName("127.0.0.1");
+        factory.setPort(6379);
+        return factory;
+    }
+
+    /**
+     * redisTemplate配置
+     *
+     * @param factory
+     * @return
+     */
+    @SuppressWarnings({"rawtypes", "unchecked"})
+    @Bean
+    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
+        StringRedisTemplate template = new StringRedisTemplate(factory);
+        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
+        ObjectMapper om = new ObjectMapper();
+        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
+        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
+        jackson2JsonRedisSerializer.setObjectMapper(om);
+        template.setValueSerializer(jackson2JsonRedisSerializer);
+        template.afterPropertiesSet();
+        return template;
+    }
+
+
+    @Bean
+    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory,
+                                            RedisMessageListener listenerAdapter) {
+        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
+        container.setConnectionFactory(connectionFactory);
+        //订阅了一个叫chat 的通道
+        container.addMessageListener(listenerAdapter, new PatternTopic(channelName));
+        //这个container 可以添加多个 messageListener
+        return container;
+    }
+
+
+}

+ 58 - 0
src/main/java/com/zx/dataservice/redismessage/listener/RedisMessageListener.java

@@ -0,0 +1,58 @@
+package com.zx.dataservice.redismessage.listener;
+
+import com.zx.dataservice.redismessage.service.MessageService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.connection.Message;
+import org.springframework.data.redis.connection.MessageListener;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Component;
+
+
+@Component
+public class RedisMessageListener implements MessageListener {
+
+    @Autowired
+    private MessageService messageService;
+
+    private static Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);
+
+    @Autowired
+    private RedisTemplate<String, String> redisTemplate;
+
+    /**
+     * 处理订阅消息
+     *
+     * @param message
+     * @param bytes
+     */
+    @Override
+    public void onMessage(Message message, byte[] bytes) {
+        // 请使用valueSerializer
+        byte[] body = message.getBody();
+        byte[] channel = message.getChannel();
+
+        String msgContent = (String) redisTemplate.getValueSerializer().deserialize(body);
+
+        String topic = redisTemplate.getStringSerializer().deserialize(channel);
+
+        //订阅消息进入队列
+        messageService.sendQueueMessage(msgContent);
+
+        logger.info("redis--topic:" + topic + "  body:" + msgContent);
+    }
+
+
+    /**
+     * 处理消息队列消息
+     */
+    //@PostConstruct
+    public void messageListener() {
+        new Thread(() -> {
+            while (true) {
+               // messageService.dealMsg();
+            }
+        }, "消息监听任务线程").start();
+    }
+}

+ 61 - 0
src/main/java/com/zx/dataservice/redismessage/service/MessageService.java

@@ -0,0 +1,61 @@
+package com.zx.dataservice.redismessage.service;
+
+import com.zx.dataservice.redismessage.util.RedisUtil;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.stereotype.Service;
+
+import java.util.concurrent.TimeUnit;
+
+
+@Service
+public class MessageService {
+
+    private static Logger logger = LoggerFactory.getLogger(MessageService.class);
+    @Autowired
+    private RedisTemplate<String, String> redisTemplate;
+
+    @Autowired
+    private RedisUtil redisUtil;
+
+    @Value("channel01")
+    private String channelName;
+
+    @Value("queuename01")
+    private String queueName;
+
+
+    /**
+     * redis发布消息
+     *
+     * @param message
+     */
+    public void sendTopicMessage(String message) {
+        redisTemplate.convertAndSend(channelName, message);
+    }
+
+    /**
+     * 处理redis消息队列
+     */
+    public String getQueueMessage(String adminName) {
+        if (null == adminName) {
+            return "no_data";
+        }
+        String message = redisUtil.rightPop(String.format("%s_%s", queueName, adminName), 1, TimeUnit.SECONDS);
+        if (null == message) {
+            // logger.info("redis--queue:" + queueName + "  body:" + message);
+            message = "no_data";
+        }
+        return message;
+    }
+
+    /**
+     * @param message
+     */
+    public void sendQueueMessage(String message) {
+
+    }
+}

+ 571 - 0
src/main/java/com/zx/dataservice/redismessage/util/RedisUtil.java

@@ -0,0 +1,571 @@
+package com.zx.dataservice.redismessage.util;
+
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.data.redis.connection.RedisConnection;
+import org.springframework.data.redis.core.Cursor;
+import org.springframework.data.redis.core.RedisTemplate;
+import org.springframework.data.redis.core.ScanOptions;
+import org.springframework.data.redis.core.ZSetOperations;
+import org.springframework.stereotype.Component;
+
+import java.io.IOException;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+
+@Component
+public class RedisUtil {
+
+    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
+
+    private static final long MAXLONG = 9007199254740992L;
+
+    /**
+     * 默认锁超时时间 30s
+     */
+    private static final long LOCK_EXPIRE = 30;
+
+    /**
+     * redis锁前缀
+     */
+    private static final String LOCK_PREFIX = "LOCK:";
+
+    @Autowired
+    private RedisTemplate<String, String> redisTemplate;
+
+    /**
+     * 保存指定键值对
+     *
+     * @param redisKey
+     * @param redisValue
+     */
+    public void saveItem(String redisKey, String redisValue) {
+        this.redisTemplate.opsForValue().set(redisKey, redisValue);
+    }
+
+    /**
+     * 保存指定时间有效的键值对
+     *
+     * @param redisKey
+     * @param redisValue
+     * @param timeout
+     * @param unit
+     */
+    public void saveItem(String redisKey, String redisValue, long timeout, TimeUnit unit) {
+        this.redisTemplate.opsForValue().set(redisKey, redisValue, timeout, unit);
+    }
+
+    /**
+     * 获取指定key的值
+     *
+     * @param redisKey
+     * @return
+     */
+    public String getItem(String redisKey) {
+        return this.redisTemplate.opsForValue().get(redisKey);
+    }
+
+    /**
+     * 获取符合正则表达式的key的集合
+     *
+     * @param keyPattern
+     * @return
+     */
+    public Set<String> keySets(String keyPattern) {
+        return this.redisTemplate.keys(keyPattern);
+    }
+
+    /**
+     * 删除指定的key
+     *
+     * @param hashKey
+     * @param rangeKey
+     */
+    public void deleteItem(String hashKey, long rangeKey) {
+        String redisKey = this.getRedisKey(hashKey, rangeKey);
+        this.redisTemplate.delete(redisKey);
+        logger.info("remove redis key:[" + redisKey + "]");
+    }
+
+    /**
+     * 删除指定的key
+     *
+     * @param redisKey
+     */
+    public void deleteItem(String redisKey) {
+        this.redisTemplate.delete(redisKey);
+        logger.debug("remove redis key:[" + redisKey + "]");
+    }
+
+    /**
+     * 删除指定的key并返回value
+     *
+     * @param redisKey
+     */
+    public String removeItem(String redisKey) {
+        logger.debug("remove redis key:[" + redisKey + "]");
+        String str = this.redisTemplate.opsForValue().get(redisKey);
+        if (null != str) {
+            this.redisTemplate.delete(redisKey);
+        }
+        return str;
+
+    }
+
+    /**
+     * 删除指定的hash key( hashKey + ":")
+     *
+     * @param hashKey
+     */
+    public void deleteItemWithHashKey(String hashKey) {
+        this.redisTemplate.delete(this.redisTemplate.keys(hashKey + ":*"));
+        logger.info("remove redis key with hashKey:[" + hashKey + "]");
+    }
+
+    /**
+     * 删除指定开始字符串的keys
+     *
+     * @param startKey
+     */
+    public void deleteItemWithStartKey(String startKey) {
+        this.redisTemplate.delete(this.redisTemplate.keys(startKey + "*"));
+        logger.info("remove redis key with hashKey:[" + startKey + "]");
+    }
+
+    /**
+     * 指定key的过期时间
+     *
+     * @param redisKey
+     * @param timeout
+     * @param unit
+     */
+    public void expireItem(String redisKey, long timeout, TimeUnit unit) {
+        this.redisTemplate.expire(redisKey, timeout, unit);
+    }
+
+    // SortedSet(有序集合)
+
+    /**
+     * 实现命令:ZADD key score member,将一个 member元素及其 score值加入到有序集 key当中。
+     *
+     * @param key
+     * @param member
+     * @param score
+     */
+    public void zAdd(String key, String member, double score) {
+        this.redisTemplate.opsForZSet().add(key, member, score);
+    }
+
+    /**
+     * zremove删除
+     *
+     * @param key
+     * @param member
+     */
+    public void zRemove(String key, String... member) {
+        this.redisTemplate.opsForZSet().remove(key, member);
+    }
+
+
+    /**
+     * 返回指定元素的索引
+     *
+     * @param key
+     * @param member
+     */
+    public Long zRank(String key, String member) {
+        return this.redisTemplate.opsForZSet().rank(key, member);
+    }
+
+
+    /**
+     * 实现命令:ZRANGE key start stop,返回有序集 key中,指定区间内的成员。
+     *
+     * @param key
+     * @param sinceIdx
+     * @param maxSize
+     * @param scanIndexForward 从前面还是后面扫描
+     * @return
+     */
+    public Set<String> zRangeByIdx(String key, long sinceIdx, long maxSize, boolean scanIndexForward) {
+        if (scanIndexForward) {
+            return this.redisTemplate.opsForZSet().range(key, sinceIdx, sinceIdx + maxSize - 1);
+        } else {
+            return this.redisTemplate.opsForZSet().reverseRange(key, sinceIdx, sinceIdx + maxSize - 1);
+        }
+    }
+
+    /**
+     * @param key
+     * @param sinceIdx
+     * @param count
+     * @param scanIndexForward
+     * @param min
+     * @param max
+     * @return
+     */
+    public Set<String> zRangeByScoreAndIdx(String key, long sinceIdx, long count, boolean scanIndexForward, long min, long max) {
+        if (scanIndexForward) {
+            return this.redisTemplate.opsForZSet().rangeByScore(key, min, max, sinceIdx, count);
+        } else {
+            return this.redisTemplate.opsForZSet().reverseRangeByScore(key, min, max, sinceIdx, count);
+        }
+    }
+
+    /**
+     * 实现命令:ZRANGE key start stop,返回有序集 key中,指定分数区间内的成员。
+     *
+     * @param key
+     * @param sinceId
+     * @param maxSize
+     * @return
+     */
+    public Set<String> zRangeByScore(String key, long sinceId, int maxSize, boolean scanIndexForward) {
+        int step = this.getStep(sinceId);
+        if (scanIndexForward) {
+            return this.redisTemplate.opsForZSet().rangeByScore(key, sinceId + step, Long.MAX_VALUE, 0, maxSize);
+        } else {
+            return this.redisTemplate.opsForZSet().reverseRangeByScore(key, 0,
+                    sinceId > 1 ? (sinceId - step) : Long.MAX_VALUE, 0, maxSize);
+        }
+    }
+
+    /**
+     * 迭代zScan,结束时需要调用关闭方法
+     *
+     * @param key
+     * @param scanOptions
+     * @return
+     */
+    public Cursor<ZSetOperations.TypedTuple<String>> zScan(String key, ScanOptions scanOptions) {
+        return redisTemplate.opsForZSet().scan(key, scanOptions);
+    }
+
+    /**
+     * 关闭
+     *
+     * @param cursor
+     */
+    public void close(Cursor<ZSetOperations.TypedTuple<String>> cursor) {
+        try {
+            cursor.close();
+        } catch (IOException e) {
+            logger.error("关闭cursor失败", e);
+        }
+    }
+
+    /**
+     * 返回zset的长度
+     *
+     * @param key
+     * @return
+     */
+    public long zSize(String key) {
+        return this.redisTemplate.opsForZSet().size(key);
+    }
+
+    /**
+     * @param hashKey
+     * @param rangeKey
+     * @return
+     */
+    public boolean hasKey(String hashKey, long rangeKey) {
+        return this.redisTemplate.hasKey(this.getRedisKey(hashKey, rangeKey));
+    }
+
+    /**
+     * @param redisKey
+     * @return
+     */
+    public boolean hasKey(String redisKey) {
+        return this.redisTemplate.hasKey(redisKey);
+    }
+
+    /**
+     * @param redisKey key
+     * @param delta    增量
+     * @return
+     */
+    public long incr(String redisKey, long delta) {
+        return this.redisTemplate.opsForValue().increment(redisKey, delta);
+    }
+
+    /**
+     * @param hashKey
+     * @param rangeKey
+     * @return
+     */
+    private String getRedisKey(String hashKey, long rangeKey) {
+        return hashKey + ":" + rangeKey;
+    }
+
+    private int getStep(long id) {
+        if (Math.abs(id) <= MAXLONG) {
+            return 1;
+        } else {
+            int step = 1;
+            while (Math.abs(id) > (MAXLONG * step)) {
+                step *= 10;
+            }
+            return step;
+        }
+    }
+
+    /**
+     * 在指定时间内尝试获取redis锁,成功返回true,失败返回false,并设置锁的过期时间
+     *
+     * @param key     锁标识
+     * @param timeout 等待获取锁的最大时间(秒)
+     * @param expire  锁过期失效时间(秒)
+     * @return
+     * @Description
+     * @author congyue.lu
+     */
+    public boolean lock(String key, long timeout, long expire) {
+        long begin = 0;
+        do {
+            if (this.tryLock(key, expire)) {
+                return true;
+            }
+            begin += 3;
+            try {
+                Thread.sleep(3000);
+            } catch (InterruptedException e) {
+                logger.error("获取锁出错", e);
+                Thread.currentThread().interrupt();
+                return false;
+            }
+        } while (begin <= timeout);
+        return false;
+    }
+
+    /**
+     * 尝试获取redis锁,成功返回true,失败返回false,并设置锁的过期时间
+     *
+     * @param key    锁标识
+     * @param expire 锁过期失效时间(秒)
+     * @return
+     * @Description
+     * @author congyue.lu
+     */
+    public boolean tryLock(String key, long expire) {
+        logger.info("try get lock for:" + key);
+        key = LOCK_PREFIX + key;
+        RedisConnection redisConnection = this.redisTemplate.getConnectionFactory().getConnection();
+        if (redisConnection.setNX(key.getBytes(), key.getBytes())) {
+            this.redisTemplate.expire(key, expire, TimeUnit.SECONDS);
+            redisConnection.close();
+            return true;
+        }
+        redisConnection.close();
+        return false;
+    }
+
+    /**
+     * 在指定时间内尝试获取redis锁,成功返回true,失败返回false
+     *
+     * @param key     锁标识
+     * @param timeout 等待获取锁的最大时间(秒)
+     * @return
+     * @Description
+     * @author congyue.lu
+     */
+    public boolean lock(String key, long timeout) {
+        return this.lock(key, timeout, LOCK_EXPIRE);
+    }
+
+    /**
+     * 尝试获取redis锁,成功返回true,失败返回false
+     *
+     * @param key 锁标识
+     * @return
+     * @Description
+     * @author congyue.lu
+     */
+    public boolean tryLock(String key) {
+        return this.tryLock(key, LOCK_EXPIRE);
+    }
+
+    /**
+     * redis锁解锁
+     *
+     * @param key 锁标识
+     * @Description
+     * @author congyue.lu
+     */
+    public void unLock(String key) {
+        key = LOCK_PREFIX + key;
+        this.redisTemplate.delete(key);
+    }
+
+
+    /**
+     * redis发布消息
+     *
+     * @param channel
+     * @param message
+     */
+    public void publish(String channel, String message) {
+        redisTemplate.convertAndSend(channel, message);
+    }
+
+    /**
+     * 获取指定区间位置的list元素
+     *
+     * @param key
+     * @return
+     */
+    public List<String> range(String key, long start, long end) {
+        return redisTemplate.opsForList().range(key, start, end);
+    }
+
+    /**
+     * 获取指定list的长度
+     *
+     * @param key
+     * @return
+     */
+    public long listSize(String key) {
+        Long size = redisTemplate.opsForList().size(key);
+        if (size == null) {
+            return 0L;
+        }
+        return size;
+    }
+
+    /**
+     * 向指定的列表左边插入数据
+     *
+     * @param key
+     * @param value
+     * @return
+     */
+    public void leftPush(String key, String value) {
+        redisTemplate.opsForList().leftPush(key, value);
+    }
+
+    /**
+     * 向指定的列表左边插入数据
+     *
+     * @param key
+     * @param value
+     * @return
+     */
+    public void rightPush(String key, String value) {
+        redisTemplate.opsForList().rightPush(key, value);
+    }
+
+    /**
+     * 弹出指定列表右边的数据
+     *
+     * @param key
+     * @return
+     */
+    public String rightPop(String key) {
+        return redisTemplate.opsForList().rightPop(key);
+    }
+
+    /**
+     * 弹出指定列表右边的数据(如果没有数据,在指定的时间内等待)
+     *
+     * @param key
+     * @param timeout
+     * @param unit
+     * @return
+     */
+    public String rightPop(String key, long timeout, TimeUnit unit) {
+        return redisTemplate.opsForList().rightPop(key, timeout, unit);
+    }
+
+
+    /**
+     * 弹出指定列表右边,并向指定列表的左边插入
+     *
+     * @param sourceKey
+     * @param destinationKey
+     * @return
+     */
+    public String rightPopAndLeftPush(String sourceKey, String destinationKey) {
+        return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey);
+    }
+
+    /**
+     * 弹出指定列表右边,并向指定列表的左边插入(弹出列表如果没有元素,等待指定的时间)
+     *
+     * @param sourceKey
+     * @param destinationKey
+     * @param timeout
+     * @param unit
+     * @return
+     */
+    public String rightPopAndLeftPush(String sourceKey, String destinationKey, long timeout, TimeUnit unit) {
+        return redisTemplate.opsForList().rightPopAndLeftPush(sourceKey, destinationKey, timeout, unit);
+    }
+
+
+    /**
+     * 存储hash形式的键值对
+     *
+     * @param key
+     * @param hash
+     * @param value
+     */
+    public void saveHashKey(String key, String hash, String value) {
+        redisTemplate.opsForHash().put(key, hash, value);
+    }
+
+    /**
+     * 存储hash形式的键值对(如果有null直接放弃存储)
+     *
+     * @param key
+     * @param hash
+     * @param value
+     */
+    public void saveHashKey4Null(String key, String hash, String value) {
+        if (null == key || null == hash || null == value) {
+            return;
+        }
+        redisTemplate.opsForHash().put(key, hash, value);
+    }
+
+    /**
+     * 删除hash
+     *
+     * @param key
+     * @param hash
+     */
+    public void delHashKey(String key, String... hash) {
+        redisTemplate.opsForHash().delete(key, hash);
+    }
+
+    /**
+     * 获取hash形式的value
+     *
+     * @param key
+     * @param hash
+     */
+    public String getHashKey(String key, String hash) {
+        Object o = redisTemplate.opsForHash().get(key, hash);
+        if (null != o) {
+            return o.toString();
+        }
+        return null;
+    }
+
+    /**
+     * 获取指定区间的zsort的数量
+     *
+     * @param key
+     * @param min
+     * @param max
+     * @return
+     */
+    public long zCount(String key, long min, long max) {
+        return this.redisTemplate.opsForZSet().count(key, min, max);
+    }
+
+
+}

+ 17 - 0
src/main/java/com/zx/dataservice/redismessage/vo/AdminVo.java

@@ -0,0 +1,17 @@
+package com.zx.dataservice.redismessage.vo;
+
+public class AdminVo {
+    public AdminVo(String adminName) {
+        this.adminName = adminName;
+    }
+
+    private String adminName;
+
+    public String getAdminName() {
+        return adminName;
+    }
+
+    public void setAdminName(String adminName) {
+        this.adminName = adminName;
+    }
+}

+ 4 - 1
src/main/java/com/zx/dataservice/task/AnalysisBondRestDataTask.java

@@ -1,5 +1,6 @@
 package com.zx.dataservice.task;
 
+import com.zx.dataservice.options.ZXOptions;
 import com.zx.dataservice.service.ChoiceBondService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -22,7 +23,9 @@ public class AnalysisBondRestDataTask {
     @Async("executorBond")
     @Scheduled(fixedRate=10)
     public void toAnalysisRestData() {
-        doTask("now");
+        if(("true").equals(ZXOptions.get("run"))){
+            doTask("now");
+        }
     }
 
     public void doTask(String type) {

+ 4 - 1
src/main/java/com/zx/dataservice/task/AnalysisStockRestDataTask.java

@@ -1,5 +1,6 @@
 package com.zx.dataservice.task;
 
+import com.zx.dataservice.options.ZXOptions;
 import com.zx.dataservice.service.ChoiceStockService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -22,7 +23,9 @@ public class AnalysisStockRestDataTask {
     @Async("executorStock")
     @Scheduled(fixedRate=10)
     public void toAnalysisRestData() {
-        doTask("now");
+        if(("true").equals(ZXOptions.get("run"))){
+            doTask("now");
+        }
     }
 
     public void doTask(String type) {

+ 4 - 1
src/main/java/com/zx/dataservice/task/AnalysisTempIndexRestDataTask.java

@@ -1,5 +1,6 @@
 package com.zx.dataservice.task;
 
+import com.zx.dataservice.options.ZXOptions;
 import com.zx.dataservice.service.ChoiceTempIndexService;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -22,7 +23,9 @@ public class AnalysisTempIndexRestDataTask {
     @Async("executorTempIndex")
     @Scheduled(fixedRate=10)
     public void toAnalysisRestData() {
-        doTask("now");
+        if(("true").equals(ZXOptions.get("run"))){
+            doTask("now");
+        }
     }
 
     public void doTask(String type) {

+ 13 - 1
src/main/java/com/zx/dataservice/utils/DateUtils.java

@@ -210,7 +210,19 @@ public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
     }
 
     public static void main(String[] args) {
-        System.out.println(getUSDate(getCurrentTime()));
+        for (int i = 0; i < 100; i++) {
+            try {
+
+                if(Integer.parseInt(DateUtils.parseDateToStr("ss",new Date()))%5==0){
+                System.out.println(getUSDate(getCurrentTime()));
+
+            }
+            Thread.sleep(1000);
+            } catch (InterruptedException e) {
+                e.printStackTrace();
+            }
+        }
+
     }
 
 

+ 60 - 0
src/main/java/com/zx/dataservice/utils/redis/CookieUtils.java

@@ -0,0 +1,60 @@
+package com.zx.dataservice.utils.redis;
+
+
+import com.zx.dataservice.utils.PropertiesUtil;
+import org.apache.commons.lang3.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.http.Cookie;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+
+public class CookieUtils {
+
+    private static final Logger log = LoggerFactory.getLogger(CookieUtils.class);
+
+
+    private static final String COOKIE_DOMAIN = PropertiesUtil.getProperty("cookie.project.url");
+
+
+    public static void writeLoginToken(HttpServletResponse httpServletResponse, String token, String COOKIE_NAME) {
+        Cookie cookie = new Cookie(COOKIE_NAME, token);
+        cookie.setPath("/");
+        cookie.setMaxAge(31536000);
+        cookie.setHttpOnly(true);
+        log.info("write cookie name :{} ,cookie value : {}", cookie.getName(), cookie.getValue());
+        httpServletResponse.addCookie(cookie);
+    }
+
+
+    public static String readLoginToken(HttpServletRequest httpServletRequest, String COOKIE_NAME) {
+        Cookie[] cookies = httpServletRequest.getCookies();
+        if (cookies != null) {
+            for (Cookie ck : cookies) {
+                if (StringUtils.equals(ck.getName(), COOKIE_NAME)) {
+                    return ck.getValue();
+                }
+            }
+        }
+        return null;
+    }
+
+
+    public static void delLoginToken(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String COOKIE_NAME) {
+        Cookie[] cookies = httpServletRequest.getCookies();
+        if (cookies != null) {
+            for (Cookie ck : cookies) {
+                if (StringUtils.equals(ck.getName(), COOKIE_NAME)) {
+                    ck.setPath("/");
+                    ck.setMaxAge(0);
+                    log.info("del cookie name : {} ,cookie value : {}", ck.getName(), ck.getValue());
+                    httpServletResponse.addCookie(ck);
+                    return;
+                }
+            }
+        }
+    }
+
+}

+ 163 - 0
src/main/java/com/zx/dataservice/utils/redis/JsonUtil.java

@@ -0,0 +1,163 @@
+package com.zx.dataservice.utils.redis;
+
+
+import org.apache.commons.lang3.StringUtils;
+import org.codehaus.jackson.map.DeserializationConfig;
+import org.codehaus.jackson.map.ObjectMapper;
+import org.codehaus.jackson.map.SerializationConfig;
+import org.codehaus.jackson.map.annotate.JsonSerialize;
+import org.codehaus.jackson.type.JavaType;
+import org.codehaus.jackson.type.TypeReference;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.text.SimpleDateFormat;
+
+
+public class JsonUtil {
+
+    private static final Logger log = LoggerFactory.getLogger(JsonUtil.class);
+
+
+    private static ObjectMapper objectMapper = new ObjectMapper();
+
+
+    static {
+
+        objectMapper.setSerializationInclusion(JsonSerialize.Inclusion.ALWAYS);
+
+
+        objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
+
+
+        objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
+
+
+        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
+
+
+        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
+
+    }
+
+
+    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) {
+
+            log.warn("XC JsonUtil Parse obj to string error ", e);
+
+            return null;
+
+        }
+
+    }
+
+
+    public static <T> String obj2StringPretty(T obj) {
+
+        if (obj == null) {
+
+            return null;
+
+        }
+
+        try {
+
+            return (obj instanceof String) ? (String) obj : objectMapper
+
+                    .writerWithDefaultPrettyPrinter().writeValueAsString(obj);
+
+        } catch (Exception e) {
+
+            log.warn("XC JsonUtil Parse obj to string error ", e);
+
+            return null;
+
+        }
+
+    }
+
+
+    public static <T> T string2Obj(String str, Class<T> clazz) {
+
+        if (StringUtils.isEmpty(str) || clazz == null) {
+
+            return null;
+
+        }
+
+        try {
+
+            return (T) (clazz.equals(String.class) ? str : objectMapper.readValue(str, clazz));
+
+        } catch (Exception e) {
+
+            log.warn("XC 1 JsonUtil Parse string to obj error", e);
+
+            return null;
+
+        }
+
+    }
+
+
+    public static <T> T string2Obj(String str, TypeReference<T> typeReference) {
+
+        if (StringUtils.isEmpty(str) || typeReference == null) {
+
+            return null;
+
+        }
+
+        try {
+
+            return (T) (typeReference.getType().equals(String.class) ? str : objectMapper
+
+                    .readValue(str, typeReference));
+
+        } catch (Exception e) {
+
+            log.warn("XC 2 JsonUtil Parse string to obj error", e);
+
+            return null;
+
+        }
+
+    }
+
+
+    public static <T> T string2Obj(String str, Class<?> collectionClass, Class... elementClasses) {
+
+        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
+
+
+        try {
+
+            return (T) objectMapper.readValue(str, javaType);
+
+        } catch (Exception e) {
+
+            log.warn("XC 3 JsonUtil Parse string to obj error", e);
+
+            return null;
+
+        }
+
+    }
+
+
+    public static void main(String[] args) {
+    }
+
+}

+ 20 - 0
src/main/java/com/zx/dataservice/utils/redis/RedisConst.java

@@ -0,0 +1,20 @@
+package com.zx.dataservice.utils.redis;
+
+
+public class RedisConst {
+    public static String getAdminRedisKey(String sessionId) {
+        return "ADMIN" + sessionId;
+    }
+
+    public static String getAgentRedisKey(String sessionId) {
+        return "AGENT" + sessionId;
+    }
+
+//    public static String getUserRedisKey(String sessionId) {
+//        return "USER" + sessionId;
+//    }
+
+    public static String getTokenRedisKey(Integer id) {
+        return "USER" + id;
+    }
+}

+ 75 - 0
src/main/java/com/zx/dataservice/utils/redis/RedisShardedPool.java

@@ -0,0 +1,75 @@
+package com.zx.dataservice.utils.redis;
+
+
+
+import java.util.List;
+
+import com.google.common.collect.Lists;
+import com.zx.dataservice.utils.PropertiesUtil;
+import redis.clients.jedis.JedisPoolConfig;
+
+import redis.clients.jedis.JedisShardInfo;
+
+import redis.clients.jedis.ShardedJedis;
+
+import redis.clients.jedis.ShardedJedisPool;
+import redis.clients.jedis.util.Hashing;
+import redis.clients.jedis.util.Sharded;
+
+
+
+
+public class RedisShardedPool {
+
+    private static ShardedJedisPool pool;
+
+    private static Integer maxTotal = Integer.valueOf(Integer.parseInt(PropertiesUtil.getProperty("redis.max.total", "20")));
+
+    private static Integer maxIdle = Integer.valueOf(Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle", "10")));
+
+    private static Integer minIdle = Integer.valueOf(Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle", "2")));
+
+    private static Boolean testOnBorrow = Boolean.valueOf(Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow", "true")));
+
+    private static Boolean testOnReturn = Boolean.valueOf(Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return", "true")));
+
+    private static String redisIp1 = PropertiesUtil.getProperty("redis1.ip");
+
+    private static Integer redisPort1 = Integer.valueOf(Integer.parseInt(PropertiesUtil.getProperty("redis1.port")));
+
+    private static void initPool() {
+        JedisPoolConfig config = new JedisPoolConfig();
+        config.setMaxTotal(maxTotal.intValue());
+        config.setMaxIdle(maxIdle.intValue());
+        config.setMinIdle(minIdle.intValue());
+        config.setTestOnBorrow(testOnBorrow.booleanValue());
+        config.setTestOnReturn(testOnReturn.booleanValue());
+        config.setBlockWhenExhausted(true);
+        List<JedisShardInfo> jedisShardInfos = Lists.newArrayList();
+        JedisShardInfo info1 = new JedisShardInfo(redisIp1, redisPort1.intValue(), 2000);
+        info1.setPassword(PropertiesUtil.getProperty("redis1.pwd"));
+        jedisShardInfos.add(info1);
+        pool = new ShardedJedisPool(config, jedisShardInfos, Hashing.MURMUR_HASH, Sharded.DEFAULT_KEY_TAG_PATTERN);
+    }
+
+    static {
+        initPool();
+    }
+
+    public static ShardedJedis getJedis() {
+        return pool.getResource();
+    }
+
+    public static void returnResouce(ShardedJedis jedis) {
+//        pool.returnResource(jedis);
+        jedis.close();
+    }
+
+    public static void returnBrokenResouce(ShardedJedis jedis) {
+//        pool.returnBrokenResource(jedis);
+        jedis.close();
+    }
+
+    public static void main(String[] args) {
+    }
+}

+ 211 - 0
src/main/java/com/zx/dataservice/utils/redis/RedisShardedPoolUtils.java

@@ -0,0 +1,211 @@
+package com.zx.dataservice.utils.redis;
+
+import com.alibaba.fastjson.JSONObject;
+import com.google.gson.Gson;
+import lombok.extern.slf4j.Slf4j;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.springframework.stereotype.Component;
+import redis.clients.jedis.ShardedJedis;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+
+@Slf4j
+@Component
+public class RedisShardedPoolUtils {
+
+    public static final int SAVE = 2;
+    public static final int GET = 1;
+    public static final int UPDATE = 0;
+    public static final int DELETE = -1;
+
+    // 注解缓存
+    public static  <T> void saveJsonCache(String key,T t){
+        ShardedJedis jedis = null;
+        String result = null;
+        String json = JSONObject.toJSONString(t);
+        try {
+            jedis = RedisShardedPool.getJedis();
+            result = jedis.set(key, json);
+        } catch (Exception e) {
+            log.error("redis set key: {} value: {} error", new Object[]{key, json, e});
+            RedisShardedPool.returnBrokenResouce(jedis);
+        }
+        RedisShardedPool.returnResouce(jedis);
+    }
+
+    public static Object getRedisJsonData(String prefix , MethodSignature signature){
+        String s = get(prefix);
+        //判断是否查询出数据,redis返回的数据是JSON格式的字符串
+        if (null!=s){
+            //获取连接点返回值类型,并将json格式字符串转成对应的类型返回
+            Class returnType = signature.getReturnType();
+            Gson gson = new Gson();
+            return gson.fromJson(s, returnType);
+        }
+        return null;
+    }
+
+    /**判断是否存在key*/
+    public boolean containKey(String key){
+        boolean b;
+        ShardedJedis jedis = null;
+        try{
+            jedis = RedisShardedPool.getJedis();
+            b = jedis.exists(key);
+            return b;
+        }catch (Exception e){
+            log.error("Redis server error::"+e.getMessage());
+            RedisShardedPool.returnBrokenResouce(jedis);
+            return false;
+        }finally {
+            RedisShardedPool.returnResouce(jedis);
+        }
+    }
+
+    public static String set(String key, String value) {
+        ShardedJedis jedis = null;
+        String result = null;
+        try {
+            jedis = RedisShardedPool.getJedis();
+            result = jedis.set(key, value);
+        } catch (Exception e) {
+            log.error("redis set key: {} value: {} error", new Object[]{key, value, e});
+            RedisShardedPool.returnBrokenResouce(jedis);
+            return result;
+        }
+        RedisShardedPool.returnResouce(jedis);
+        return result;
+    }
+
+    public static String get(String key) {
+        ShardedJedis jedis = null;
+        String result = null;
+        try {
+            jedis = RedisShardedPool.getJedis();
+            result = jedis.get(key);
+        } catch (Exception e) {
+            log.error("redis get key: {} error", key, e);
+            RedisShardedPool.returnBrokenResouce(jedis);
+            return result;
+        }
+        RedisShardedPool.returnResouce(jedis);
+        return result;
+    }
+
+    public static String setEx(String key, String value, int exTime) {
+        ShardedJedis jedis = null;
+        String result = null;
+        try {
+            jedis = RedisShardedPool.getJedis();
+            result = jedis.setex(key, exTime, value);
+        } catch (Exception e) {
+            log.error("redis setEx key: {} value: {}   error...", new Object[]{key, value, e});
+            RedisShardedPool.returnBrokenResouce(jedis);
+            return result;
+        }
+        RedisShardedPool.returnResouce(jedis);
+        return result;
+    }
+
+    public static Long expire(String key, int exTime) {
+        ShardedJedis jedis = null;
+        Long result = null;
+        try {
+            jedis = RedisShardedPool.getJedis();
+            result = jedis.expire(key, exTime);
+        } catch (Exception e) {
+            log.error("redis expire key: {}  error ", key, e);
+            RedisShardedPool.returnBrokenResouce(jedis);
+            return result;
+        }
+        RedisShardedPool.returnResouce(jedis);
+        return result;
+    }
+
+    public static Long del(String key) {
+        ShardedJedis jedis = null;
+        Long result = null;
+        try {
+            jedis = RedisShardedPool.getJedis();
+            result = jedis.del(key);
+        } catch (Exception e) {
+            log.error("redis del key: {} error ", key, e);
+            RedisShardedPool.returnBrokenResouce(jedis);
+            return result;
+        }
+        RedisShardedPool.returnResouce(jedis);
+        return result;
+    }
+
+    public static <T> void setObject(String key,T t){
+        ShardedJedis jedis = null;
+        T result = null;
+        try {
+            jedis = RedisShardedPool.getJedis();
+            jedis.set(key.getBytes(),serialize(t));
+        } catch (Exception e) {
+            log.error("redis set key: {} value: {} error", new Object[]{key, t, e});
+            RedisShardedPool.returnBrokenResouce(jedis);
+        }
+        RedisShardedPool.returnResouce(jedis);
+    }
+
+    public static <T> T getObject(String key, T t){
+        ShardedJedis jedis = null;
+        T result = null;
+        try {
+            jedis = RedisShardedPool.getJedis();
+            byte[] bytes = jedis.get(key.getBytes());
+            if(null!=bytes && bytes.length>0){
+                result = unserialize(bytes,t);
+            }
+        } catch (Exception e) {
+            log.error("redis get key: {} value: {} error", new Object[]{key, t, e});
+            RedisShardedPool.returnBrokenResouce(jedis);
+            return result;
+        }
+        RedisShardedPool.returnResouce(jedis);
+        return result;
+    }
+
+    //序列化
+    public static <T> byte[] serialize(T object) {
+        ObjectOutputStream oos = null;
+        ByteArrayOutputStream baos = null;
+        try {
+            baos = new ByteArrayOutputStream();
+            oos = new ObjectOutputStream(baos);
+            oos.writeObject(object);
+            byte[] bytes = baos.toByteArray();
+            return bytes;
+        } catch (Exception e) {
+            log.error("序列化失败:{}",e);
+        }
+        return null;
+    }
+
+    //反序列化
+    public static <T> T unserialize(byte[] bytes, T t) {
+        ByteArrayInputStream bais = null;
+        try {
+            bais = new ByteArrayInputStream(bytes);
+            ObjectInputStream ois = new ObjectInputStream(bais);
+            return (T)ois.readObject();
+        } catch (Exception e) {
+            log.error("反序列化失败:{}",e);
+        }
+        return null;
+    }
+
+    public static void main(String[] args) {
+        ShardedJedis jedis = RedisShardedPool.getJedis();
+        System.out.println(get("key1"));
+        System.out.println(get("key2"));
+        System.out.println(get("key3"));
+        System.out.println("redis shaded pool utils end ...");
+    }
+
+}

File diff ditekan karena terlalu besar
+ 254 - 0
src/main/java/com/zx/dataservice/vo/StockVO.java