POM.xml

  1. <!--*******************redis*************************-->
  2. <dependency>
  3. <groupId>redis.clients</groupId>
  4. <artifactId>jedis</artifactId>
  5. <version>2.9.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework.data</groupId>
  9. <artifactId>spring-data-redis</artifactId>
  10. <version>1.5.0.RELEASE</version>
  11. </dependency>
  12. <!--*******************end redis*************************-->

application.yml

#172.16.1.19  192.168.1.55
redis:
  hostName: localhost
  port: 6379
  #Pass2017
  password:
  timeout: 5000
  maxTotal: 600
  maxIdle: 300
  minIdle: 10
  maxWaitMillis: 2000
  testOnBorrow: true
  testOnReturn: true

RedisProperty

将application.yml中的配置映射成java bean

package com.soyuan.cnrz.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "redis")
@Data
public class RedisProperty {
    private String hostName;
    private int port;
    private String password;
    private int timeout;
    private int maxTotal;
    private int maxIdle;
    private int minIdle;
    private int maxWaitMillis;
    private boolean testOnBorrow;
    private boolean testOnReturn;
}

RedisConfig

package com.soyuan.cnrz.config;

import com.soyuan.cnrz.redis.PushContainerNumberAction;
import com.soyuan.cnrz.redis.RedisAutoStarter;
import com.soyuan.cnrz.redis.RedisMessageListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfig {

    @Autowired
    private RedisProperty redisProperty;

    //配置线程池
    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(redisConfig.getMaxTotal());
        config.setMaxIdle(redisConfig.getMaxIdle());
        config.setMinIdle(redisConfig.getMinIdle());
        config.setMaxWaitMillis(redisConfig.getMaxWaitMillis());
        config.setTestOnBorrow(redisConfig.isTestOnBorrow());
        config.setTestOnReturn(redisConfig.isTestOnReturn());
        return  config;
    }

    //配置连接工厂
    @Bean(name = "myJedisFactory")
    public JedisConnectionFactory factory(){
        JedisConnectionFactory factory = new JedisConnectionFactory();
        factory.setHostName(redisConfig.getHostName());
        factory.setPort(redisConfig.getPort());
        factory.setPoolConfig(jedisPoolConfig());
        factory.setTimeout(redisConfig.getTimeout());
        factory.setUsePool(true);
        factory.setPassword(redisConfig.getPassword());
        return  factory;
    }

    @Bean
    public PushContainerNumberAction pushAction(){
        return new PushContainerNumberAction();
    }

    @Bean(name = "messageListener",initMethod = "init")
    public RedisMessageListener listener(){
        return new RedisMessageListener();
    }

    @Bean(initMethod = "start")
    public RedisAutoStarter starter(){
        return new RedisAutoStarter();
    }
}

RedisAutoStarter

  1. 在RedisConfig中配置了此Bean初始化的方法,所以程序启动后会自动调用start方法。

  2. 最最重要的是注入 RedisConnectionFactory 连接工厂

  3. 获取连接后 connection.subscribe(messageListener,channelName.getBytes()); 传入一个监听器即可

package com.soyuan.cnrz.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

@Component
public class RedisAutoStarter {
    private static final Logger logger = LoggerFactory.getLogger(RedisAutoStarter.class);

    @Autowired
    @Qualifier("messageListener")
    private RedisMessageListener messageListener;

    @Autowired
    @Qualifier("myJedisFactory")
    private RedisConnectionFactory connectionFactory;

    @Value("${channelName}")
    private String channelName;

    @Value("${isOpen}")
    private Boolean openRedis;

    public void start() {
        if (openRedis) {
            logger.info("智能识别服务已启动..."+channelName);
            final RedisConnection connection;
            try{
                connection = connectionFactory.getConnection();
                messageListener.listenTime();

                new Thread(()->{
                    connection.subscribe(messageListener,channelName.getBytes());
                }).start();
            }catch (Exception e){
                logger.error("【获取redis连接出错】->{}",e.getMessage());
            }
        }else{
          logger.info("暂未开启智能识别服务");
         }
    }
}
package com.soyuan.cnrz.redis;

import com.google.common.base.Strings;
import com.google.common.collect.ArrayListMultimap;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.soyuan.cnrz.callback.BasicCallBack;
import okhttp3.Call;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
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.connection.Message;
import org.springframework.data.redis.connection.MessageListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

public class RedisMessageListener implements MessageListener {
    private static final Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);

    public RedisMessageListener() {
    }

    public void init(){

    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String result = new String(message.getBody(), Charset.forName("utf-8"));
    }


    /**
     * 每隔10秒(由monitorContainerNumPassOffPluse设置)执行一次这个方法
     ****************************************************
     *  mapExit存储的是 查验位最后一次收到redis消息的时间
     *  *************************************************
     *  该方法 计算 【当前时间和最后一次收到redis消息的时间】的差值
     *  如果这个差值大于我们设置的秒数(receiveAndSendBufferTime),
     *  说明该查验位已经有很久没检测到集装箱号了,间接地说明集装箱已拖走--出场状态
     */
    public void listenTime(){
        logger.info("listenTime method enter....");
        new Thread(() ->{
            while (true){
                try {
                    //间隔多少秒检测一次能否识别到集装箱号
                    Thread.sleep(monitorContainerNumPassOffPluse);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
        }).start();
    }
}

MVC版本

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       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"
       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.xsd">

    <context:property-placeholder location="classpath:redis.properties"/>

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.maxTotal}"></property>
        <property name="maxIdle" value="${redis.maxIdle}"></property>
        <property name="minIdle" value="${redis.minIdle}"></property>
        <property name="maxWaitMillis" value="${redis.maxWaitMillis}"></property>

        <property name="testOnBorrow" value="${redis.testOnBorrow}"></property>
        <property name="testOnReturn" value="${redis.testOnReturn}"></property>
    </bean>


    <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:hostName="${redis.hostName}"
        p:port="${redis.port}" p:poolConfig-ref="jedisPoolConfig" p:timeout="${redis.timeout}" p:usePool="true" p:password="${redis.password}" />


    <!-- Redis Template -->
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
        <property name="connectionFactory" ref="jedisConnectionFactory"/>
    </bean>

    <bean class="com.soyuan.redis.PushContainerNumberAction" />
    <bean id="messageListener" class="com.soyuan.redis.RedisMessageListener" init-method="init" />
    <bean class="com.soyuan.redis.RedisAutoStarter" init-method="start"/>
</beans>