package com.weiqi.mis; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; import java.util.function.Consumer; /** * Created by sky on 2019/7/24. */ @Configuration //@PropertySource("classpath:redis.properties") public class RedisUtil { @Value("${spring.redis.host:192.168.0.1}") private String host; @Value("${spring.redis.port:6793}") private int port; @Value("${spring.redis.timeout:5000}") private int timeout; @Value("${spring.redis.jedis.pool.max-idle:1}") private int maxIdle; @Value("${spring.redis.jedis.pool.max-wait:0}") private long maxWaitMillis; @Value("${spring.redis.block-when-exhausted:0}") private boolean blockWhenExhausted; @Bean public JedisPool redisPoolFactory() throws Exception{ JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(maxIdle); jedisPoolConfig.setMaxWaitMillis(maxWaitMillis); // 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted); // 是否启用pool的jmx管理功能, 默认true jedisPoolConfig.setJmxEnabled(true); JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout); return jedisPool; } public static JedisPool pool=null; @Autowired void init(JedisPool _pool) { pool=_pool; } public static void call(Consumer fun) { try (Jedis jedis = pool.getResource()) { fun.accept(jedis); } } private static final String SCRIPT="local t= redis.call('time')[1]\n return redis.call('incrby',KEYS[1]..':'..KEYS[2]..':'..t,ARGV[1])"; public static Long qpsOK(String key, Integer value) { try (Jedis jedis = pool.getResource()) { return (Long) jedis.eval(SCRIPT,2,"incrOK",key, String.valueOf(value)); } } public static Long qpsERROR(String key, Integer value) { try (Jedis jedis = pool.getResource()) { return (Long) jedis.eval(SCRIPT,2,"incrERROR",key, String.valueOf(value)); } } }