├── .gitignore ├── src ├── main │ └── java │ │ └── com │ │ └── x9710 │ │ └── common │ │ └── redis │ │ ├── MessageConsumer.java │ │ ├── MessagePublisher.java │ │ ├── domain │ │ ├── GeoCoordinate.java │ │ └── Postion.java │ │ ├── LockService.java │ │ ├── LBSService.java │ │ ├── UUIDService.java │ │ ├── impl │ │ ├── MessageConsumerRedisImpl.java │ │ ├── MessagePublisherRedisImpl.java │ │ ├── UUIDServiceRedisImpl.java │ │ ├── LBSServiceRedisImpl.java │ │ ├── LockServiceRedisImpl.java │ │ └── CacheServiceRedisImpl.java │ │ ├── CacheService.java │ │ ├── SerializeUtil.java │ │ └── RedisConnection.java └── test │ └── java │ └── com │ └── x9710 │ └── common │ └── redis │ └── test │ ├── RedisConsumerTest.java │ ├── RedisConnectionTest.java │ ├── RedisConnectionUtil.java │ ├── RedisPublisherTest.java │ ├── domain │ └── Student.java │ ├── RedisLockTest.java │ ├── RedisUUIDTest.java │ ├── RedisCacheTest.java │ └── RedisLBSTest.java ├── README.md ├── pom.xml └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .idea 3 | /**/target/ -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/MessageConsumer.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis; 2 | 3 | /** 4 | * 消息消费者服务接口 5 | * 6 | * @author 杨高超 7 | * @since 2018-01-03 8 | */ 9 | public interface MessageConsumer { 10 | void handleMessage(String message); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/MessagePublisher.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis; 2 | 3 | /** 4 | * 消息生产者服务接口 5 | * 6 | * @author 杨高超 7 | * @since 2018-01-03 8 | */ 9 | public interface MessagePublisher { 10 | boolean sendMessage(String message); 11 | } 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## 说明 2 | 3 | 本模块实现了 redis 的通用工具类 4 | 5 | ### 本地安装 6 | 7 | 1. 环境要求 8 | * 必须安装 git 客户端 9 | * 必须安装 JDK1.8 10 | * 设置 JAVA_HOME 和 MVN_HOMME 环境变量 11 | * 设置 PATH 环境变量,确保 JAVA_HOEM/bin 目录和 MVN_HOMME/bin 目录在PATH环境变量中 12 | 13 | 2. 执行命令 14 | 15 | git clone git@github.com:gaochao2000/redis_util.git 16 | git branch dev origin/dev 17 | git checkout dev 18 | mvn install 19 | 20 | ### maven 依赖配置 21 | 22 | 23 | com.x9710.common 24 | redis-util 25 | 1.0-SNAPSHOT 26 | 27 | 28 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/domain/GeoCoordinate.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.domain; 2 | 3 | /** 4 | * 一个地理坐标对象 5 | * 6 | * @author 杨高超 7 | * @since 2017-12-26 8 | */ 9 | public class GeoCoordinate { 10 | /** 11 | * 经度 12 | */ 13 | private Double longitude; 14 | /** 15 | * 纬度 16 | */ 17 | private Double latitude; 18 | 19 | public Double getLongitude() { 20 | return longitude; 21 | } 22 | 23 | public void setLongitude(Double longitude) { 24 | this.longitude = longitude; 25 | } 26 | 27 | public Double getLatitude() { 28 | return latitude; 29 | } 30 | 31 | public void setLatitude(Double latitude) { 32 | this.latitude = latitude; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/RedisConsumerTest.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import com.x9710.common.redis.impl.MessageConsumerRedisImpl; 5 | import org.junit.Test; 6 | 7 | /** 8 | * 消息消费服务测试类 9 | * 10 | * @author 杨高超 11 | * @since 2018-01-03 12 | */ 13 | public class RedisConsumerTest { 14 | 15 | @Test 16 | public void consumerTest() { 17 | RedisConnection redisConnection = RedisConnectionUtil.create(); 18 | new MessageConsumerRedisImpl(redisConnection, new String[]{"channel1", "channel2"}) { 19 | public void handleMessage(String message) { 20 | System.out.println(message); 21 | } 22 | }; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/LockService.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis; 2 | 3 | /** 4 | * 分布式锁接口 5 | * 6 | * @author 杨高超 7 | * @since 2017-12-14 8 | */ 9 | public interface LockService { 10 | /** 11 | * 通过一个key 立刻获取锁 12 | * 13 | * @param key 获取锁的 key 14 | * @return 如果获取成功返回锁定值,否则返回 null 15 | */ 16 | String lock(String key); 17 | 18 | /** 19 | * 通过一个key 再超时时间内获取锁,如果不能马上获取锁,则等待获取,直到时间超时 20 | * 21 | * @param key 获取锁的 key 22 | * @return 如果获取成功返回锁定值,否则返回 null 23 | */ 24 | String tryLock(String key); 25 | 26 | /** 27 | * 解锁一个分布式锁 28 | * 29 | * @param key 分布式锁 key 30 | * @param value 获取分布式式锁的时候获取到的值,只有用获取锁时,获取到的锁定值才能解锁。 31 | * @return 是否解锁成功 32 | */ 33 | boolean unLock(String key, String value); 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/LBSService.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis; 2 | 3 | import com.x9710.common.redis.domain.GeoCoordinate; 4 | import com.x9710.common.redis.domain.Postion; 5 | 6 | import java.util.List; 7 | 8 | /** 9 | * 位置服务接口 10 | * 11 | * @author 杨高超 12 | * @since 2017-12-26 13 | */ 14 | public interface LBSService { 15 | 16 | /** 17 | * 存储一个位置 18 | * 19 | * @param postion 增加的位置对象 20 | * @throws Exception 21 | */ 22 | boolean addPostion(Postion postion); 23 | 24 | /** 25 | * 查询以指定的坐标为中心,指定的距离为半径的范围类的所有位置点 26 | * 27 | * @param center 中心点位置 28 | * @param distinct 最远距离,单位米 29 | * @param asc 是否倒序排序 30 | * @return 有效的位置 31 | */ 32 | List radious(String type, GeoCoordinate center, Long distinct, Boolean asc); 33 | } 34 | -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/RedisConnectionTest.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import org.junit.Assert; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import redis.clients.jedis.Jedis; 8 | 9 | /** 10 | * redis 连接测试类 11 | * 12 | * @author 杨高超 13 | * @since 2017-12-09 14 | */ 15 | public class RedisConnectionTest { 16 | private RedisConnection redisConnection; 17 | 18 | @Before 19 | public void before() { 20 | redisConnection = RedisConnectionUtil.create(); 21 | } 22 | 23 | @Test 24 | public void testPutGet() { 25 | Jedis jedis = redisConnection.getJedis(); 26 | try { 27 | jedis.select(1); 28 | jedis.set("name", "grace"); 29 | Assert.assertTrue("grace".equals(jedis.get("name"))); 30 | } finally { 31 | if (jedis != null) { 32 | jedis.close(); 33 | } 34 | } 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/UUIDService.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis; 2 | 3 | /** 4 | * 全局唯一标识服务接口 5 | * 6 | * @author 杨高超 7 | * @since 2017-12-10 8 | */ 9 | public interface UUIDService { 10 | 11 | /** 12 | * 每天从 1 开始生成唯一标识 13 | * 14 | * @param key 要生成唯一标识的对象 15 | * @param length 要生成为唯一标识后缀的长度。不包括需要附加的时间前缀 16 | * 如果 haveDay = false 或者 length 长度小于标识后缀的长度则无效 17 | * @param haveDay 是否要附加日期前缀 18 | * @return 唯一标识 19 | * @throws Exception 异常 20 | */ 21 | Long fetchDailyUUID(String key, Integer length, Boolean haveDay) throws Exception; 22 | 23 | /** 24 | * 全局从 1 开始生成唯一标识 25 | * 26 | * @param key 要生成唯一标识的对象 27 | * @param length 要生成为唯一标识后缀的长度。不包括需要附加的时间前缀 28 | * 如果 haveDay = false 或者 length 长度小于标识后缀的长度则无效 29 | * @param haveDay 是否要附加日期前缀。 30 | * @return 唯一标识 31 | * @throws Exception 异常 32 | */ 33 | Long fetchUUID(String key, Integer length, Boolean haveDay) throws Exception; 34 | } -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/RedisConnectionUtil.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import redis.clients.jedis.JedisPoolConfig; 5 | 6 | /** 7 | * redis 连接测试辅助类 8 | * 9 | * @author 杨高超 10 | * @since 2017-12-09 11 | */ 12 | public class RedisConnectionUtil { 13 | public static RedisConnection create() { 14 | JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); 15 | jedisPoolConfig.setMaxTotal(50); 16 | jedisPoolConfig.setMaxIdle(10); 17 | jedisPoolConfig.setMinIdle(1); 18 | RedisConnection redisConnection = new RedisConnection(); 19 | redisConnection.setIp("10.110.2.56"); 20 | redisConnection.setPort(52981); 21 | redisConnection.setPwd("hhSbcpotThgWdnxJNhrzwstSP20DvYOldkjf"); 22 | redisConnection.setClientName(Thread.currentThread().getName()); 23 | redisConnection.setTimeOut(600); 24 | redisConnection.setJedisPoolConfig(jedisPoolConfig); 25 | return redisConnection; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/RedisPublisherTest.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import com.x9710.common.redis.impl.MessagePublisherRedisImpl; 5 | import org.junit.Assert; 6 | import org.junit.Before; 7 | import org.junit.Test; 8 | 9 | /** 10 | * 消息发送服务测试类 11 | * 12 | * @author 杨高超 13 | * @since 2018-01-03 14 | */ 15 | public class RedisPublisherTest { 16 | private MessagePublisherRedisImpl messagePublisherRedis; 17 | 18 | @Before 19 | public void before() { 20 | RedisConnection redisConnection = RedisConnectionUtil.create(); 21 | messagePublisherRedis = new MessagePublisherRedisImpl(); 22 | messagePublisherRedis.setRedisConnection(redisConnection); 23 | messagePublisherRedis.setChannels(new String[]{"channel1", "channel2"}); 24 | } 25 | 26 | @Test 27 | public void publisherTest() { 28 | for (int i = 0; i < 3; i++) { 29 | Assert.assertTrue(messagePublisherRedis.sendMessage("message" + i)); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.x9710.common 8 | redis-util 9 | 1.0-SNAPSHOT 10 | 11 | 12 | commons-logging 13 | commons-logging 14 | 1.1.1 15 | 16 | 17 | log4j 18 | log4j 19 | 1.2.17 20 | 21 | 22 | redis.clients 23 | jedis 24 | 2.9.0 25 | 26 | 27 | 28 | junit 29 | junit 30 | 4.12 31 | test 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/impl/MessageConsumerRedisImpl.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.impl; 2 | 3 | import com.x9710.common.redis.MessageConsumer; 4 | import com.x9710.common.redis.RedisConnection; 5 | import redis.clients.jedis.Jedis; 6 | import redis.clients.jedis.JedisPubSub; 7 | 8 | /** 9 | * 消息消费者服务 redis 实现类 10 | * 11 | * @author 杨高超 12 | * @since 2018-01-03 13 | */ 14 | public abstract class MessageConsumerRedisImpl implements MessageConsumer { 15 | 16 | /** 17 | * 18 | * @param redisConnection redis 连接类 19 | * @param channels 订阅的频道列表 20 | */ 21 | public MessageConsumerRedisImpl(RedisConnection redisConnection, String[] channels) { 22 | Jedis jedis = null; 23 | try { 24 | if (channels != null && channels.length > 0) { 25 | jedis = redisConnection.getJedis(); 26 | jedis.subscribe(new JedisPubSub() { 27 | @Override 28 | public void onMessage(String channel, String message) { 29 | System.out.println("receive " + message + " from " + channel); 30 | handleMessage(message); 31 | } 32 | }, channels); 33 | } 34 | } catch (Exception e) { 35 | e.printStackTrace(); 36 | } finally { 37 | if (jedis != null) { 38 | jedis.close(); 39 | } 40 | } 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/impl/MessagePublisherRedisImpl.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.impl; 2 | 3 | import com.x9710.common.redis.MessagePublisher; 4 | import com.x9710.common.redis.RedisConnection; 5 | import redis.clients.jedis.Jedis; 6 | 7 | /** 8 | * 消息生产者服务 redis 实现类 9 | * 10 | * @author 杨高超 11 | * @since 2018-01-03 12 | */ 13 | public class MessagePublisherRedisImpl implements MessagePublisher { 14 | private RedisConnection redisConnection; 15 | 16 | /** 17 | * 可以同时向多个频道发送数据 18 | */ 19 | private String[] channels; 20 | 21 | public void setRedisConnection(RedisConnection redisConnection) { 22 | this.redisConnection = redisConnection; 23 | } 24 | 25 | public void setChannels(String[] channels) { 26 | this.channels = channels; 27 | } 28 | 29 | public boolean sendMessage(String message) { 30 | Jedis jedis = null; 31 | try { 32 | if (channels != null && channels.length > 0) { 33 | jedis = redisConnection.getJedis(); 34 | for (String channel : channels) { 35 | jedis.publish(channel, message); 36 | } 37 | return true; 38 | } 39 | } catch (Exception e) { 40 | e.printStackTrace(); 41 | } finally { 42 | if (jedis != null) { 43 | jedis.close(); 44 | } 45 | } 46 | return false; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/CacheService.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis; 2 | 3 | /** 4 | * 缓存服务接口 5 | * 6 | * @author 杨高超 7 | * @since 2017-12-09 8 | */ 9 | public interface CacheService { 10 | 11 | /** 12 | * 将对象存放到缓存中 13 | * 14 | * @param key 存放的 key 15 | * @param value 存放的值 16 | */ 17 | void putObject(String key, Object value); 18 | 19 | /** 20 | * 将对象存放到缓存中 21 | * 22 | * @param key 存放的 key 23 | * @param value 存放的值 24 | * @param expiration 过期时间,单位秒 25 | */ 26 | void putObject(String key, Object value, int expiration); 27 | 28 | /** 29 | * 从缓存中获取对象 30 | * 31 | * @param key 要获取对象的 key 32 | * @return 如果存在,返回对象,否则,返回 null 33 | */ 34 | Object pullObject(String key); 35 | 36 | /** 37 | * 给缓存对象设置过期秒数 38 | * 39 | * @param key 要获取对象的 key 40 | * @param expireSecond 过期秒数 41 | * @return 如果存在,返回对象,否则,返回 null 42 | */ 43 | boolean expire(String key, int expireSecond); 44 | 45 | /** 46 | * 获取缓存对象过期秒数 47 | * 48 | * @param key 要获取对象的 key 49 | * @return 如果对象不存在,返回-2,如果对象没有过期时间,返回-1,否则返回实际过期时间 50 | */ 51 | Long ttl(String key); 52 | 53 | /** 54 | * 从缓存中删除对象 55 | * 56 | * @param key 要删除对象的 key 57 | * @return 如果出现错误,返回 false,否则返回 true 58 | */ 59 | boolean delObject(String key); 60 | 61 | /** 62 | * 从缓存中清除对象 63 | */ 64 | 65 | void clearObject(); 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/SerializeUtil.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis; 2 | 3 | import java.io.ByteArrayInputStream; 4 | import java.io.ByteArrayOutputStream; 5 | import java.io.ObjectInputStream; 6 | import java.io.ObjectOutputStream; 7 | 8 | /** 9 | * 对象序列化工具类 10 | * 11 | * @author 杨高超 12 | * @since 2017-10-09 13 | */ 14 | public class SerializeUtil { 15 | 16 | /** 17 | * 将一个对象序列化为二进制数组 18 | * 19 | * @param object 要序列化的对象,该必须实现 java.io.Serializable 接口 20 | * @return 被序列化后的二进制数组 21 | */ 22 | public static byte[] serialize(Object object) { 23 | 24 | try { 25 | ByteArrayOutputStream baos = new ByteArrayOutputStream(); 26 | ObjectOutputStream oos = new ObjectOutputStream(baos); 27 | oos.writeObject(object); 28 | return baos.toByteArray(); 29 | 30 | } catch (Exception e) { 31 | e.printStackTrace(); 32 | } 33 | return null; 34 | } 35 | 36 | /** 37 | * 将一个二进制数组反序列化为一个对象。程序不检查反序列化过程中的对象类型。 38 | * 39 | * @param bytes 要反序列化的二进制数 40 | * @return 反序列化后的对象 41 | */ 42 | public static Object unserialize(byte[] bytes) { 43 | try { 44 | ByteArrayInputStream bais = new ByteArrayInputStream(bytes); 45 | ObjectInputStream ois = new ObjectInputStream(bais); 46 | return ois.readObject(); 47 | } catch (Exception e) { 48 | e.printStackTrace(); 49 | } 50 | return null; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/domain/Postion.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.domain; 2 | 3 | /** 4 | * 一个位置对象 5 | * 6 | * @author 杨高超 7 | * @since 2017-12-26 8 | */ 9 | public class Postion { 10 | /** 11 | * 位置的标识 12 | */ 13 | private String id; 14 | /** 15 | * 位置的类型 16 | */ 17 | private String type; 18 | /** 19 | * 位置的坐标点 20 | */ 21 | private GeoCoordinate coordinate; 22 | 23 | /** 24 | * 距离 25 | */ 26 | private Double distinct; 27 | 28 | public Postion(String id, String type, Double longitude, Double latitude) { 29 | this.id = id; 30 | this.type = type; 31 | coordinate = new GeoCoordinate(); 32 | coordinate.setLongitude(longitude); 33 | coordinate.setLatitude(latitude); 34 | } 35 | 36 | public String getId() { 37 | return id; 38 | } 39 | 40 | public void setId(String id) { 41 | this.id = id; 42 | } 43 | 44 | public String getType() { 45 | return type; 46 | } 47 | 48 | public void setType(String type) { 49 | this.type = type; 50 | } 51 | 52 | public GeoCoordinate getCoordinate() { 53 | return coordinate; 54 | } 55 | 56 | public void setCoordinate(GeoCoordinate coordinate) { 57 | this.coordinate = coordinate; 58 | } 59 | 60 | public Double getDistinct() { 61 | return distinct; 62 | } 63 | 64 | public void setDistinct(Double distinct) { 65 | this.distinct = distinct; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/domain/Student.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test.domain; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * 缓存测试缓存对象类 7 | * 8 | * @author 杨高超 9 | * @since 2017-12-09 10 | */ 11 | public class Student implements Serializable { 12 | private String id; 13 | private String name; 14 | private Integer age; 15 | 16 | public String getId() { 17 | return id; 18 | } 19 | 20 | public void setId(String id) { 21 | this.id = id; 22 | } 23 | 24 | public String getName() { 25 | return name; 26 | } 27 | 28 | public void setName(String name) { 29 | this.name = name; 30 | } 31 | 32 | public Integer getAge() { 33 | return age; 34 | } 35 | 36 | public void setAge(Integer age) { 37 | this.age = age; 38 | } 39 | 40 | @Override 41 | public boolean equals(Object o) { 42 | if (this == o) return true; 43 | if (o == null || getClass() != o.getClass()) return false; 44 | 45 | Student student = (Student) o; 46 | 47 | if (id != null ? !id.equals(student.id) : student.id != null) return false; 48 | if (name != null ? !name.equals(student.name) : student.name != null) return false; 49 | return age != null ? age.equals(student.age) : student.age == null; 50 | } 51 | 52 | @Override 53 | public int hashCode() { 54 | int result = id != null ? id.hashCode() : 0; 55 | result = 31 * result + (name != null ? name.hashCode() : 0); 56 | result = 31 * result + (age != null ? age.hashCode() : 0); 57 | return result; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/RedisLockTest.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import com.x9710.common.redis.impl.LockServiceRedisImpl; 5 | 6 | public class RedisLockTest { 7 | 8 | public static void main(String[] args) { 9 | for (int i = 0; i < 9; i++) { 10 | new Thread(new Runnable() { 11 | public void run() { 12 | RedisConnection redisConnection = RedisConnectionUtil.create(); 13 | LockServiceRedisImpl lockServiceRedis = new LockServiceRedisImpl(); 14 | lockServiceRedis.setRedisConnection(redisConnection); 15 | lockServiceRedis.setDbIndex(15); 16 | lockServiceRedis.setLockExpirseTime(20); 17 | String key = "20171228"; 18 | String value = lockServiceRedis.lock(key); 19 | try { 20 | if (value != null) { 21 | System.out.println(Thread.currentThread().getName() + " lock key = " + key + " success! "); 22 | Thread.sleep(2 * 1000); 23 | } else { 24 | System.out.println(Thread.currentThread().getName() + " lock key = " + key + " failure! "); 25 | } 26 | } catch (Exception e) { 27 | e.printStackTrace(); 28 | } finally { 29 | if (value == null) { 30 | value = ""; 31 | } 32 | System.out.println(Thread.currentThread().getName() + " unlock key = " + key + " " + lockServiceRedis.unLock(key, value)); 33 | 34 | } 35 | } 36 | }).start(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/RedisConnection.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis; 2 | 3 | import redis.clients.jedis.Jedis; 4 | import redis.clients.jedis.JedisPool; 5 | import redis.clients.jedis.JedisPoolConfig; 6 | 7 | /** 8 | * Redis 连接类 9 | * 10 | * @author 杨高超 11 | * @since 2017-12-09 12 | */ 13 | public class RedisConnection { 14 | /** 15 | * redis 连接池配置信息 16 | */ 17 | private JedisPoolConfig jedisPoolConfig; 18 | /** 19 | * redis 服务器地址 20 | */ 21 | private String ip; 22 | 23 | /** 24 | * redis 服务器端口 25 | */ 26 | private Integer port; 27 | 28 | /** 29 | * redis 服务器密码 30 | */ 31 | private String pwd; 32 | 33 | /** 34 | * redis 服务器连接超时时间 35 | */ 36 | private Integer timeOut; 37 | 38 | /** 39 | * redis 连接客户端名称 40 | */ 41 | private String clientName = null; 42 | 43 | private JedisPool jedisPool; 44 | 45 | public void setJedisPoolConfig(JedisPoolConfig jedisPoolConfig) { 46 | this.jedisPoolConfig = jedisPoolConfig; 47 | } 48 | 49 | public void setIp(String ip) { 50 | this.ip = ip; 51 | } 52 | 53 | public void setPort(Integer port) { 54 | this.port = port; 55 | } 56 | 57 | public void setPwd(String pwd) { 58 | this.pwd = pwd; 59 | } 60 | 61 | public void setTimeOut(Integer timeOut) { 62 | this.timeOut = timeOut; 63 | } 64 | 65 | public void setClientName(String clientName) { 66 | this.clientName = clientName; 67 | } 68 | 69 | private void buildConnection() { 70 | if (jedisPool == null) { 71 | if (jedisPoolConfig == null) { 72 | jedisPool = new JedisPool(new JedisPoolConfig(), ip, port, timeOut, pwd, 0, clientName); 73 | } else { 74 | jedisPool = new JedisPool(jedisPoolConfig, ip, port, timeOut, pwd, 0, clientName); 75 | } 76 | } 77 | } 78 | 79 | public Jedis getJedis() { 80 | buildConnection(); 81 | if (jedisPool != null) { 82 | return jedisPool.getResource(); 83 | } 84 | return null; 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/RedisUUIDTest.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import com.x9710.common.redis.impl.UUIDServiceRedisImpl; 5 | 6 | import java.util.Date; 7 | 8 | public class RedisUUIDTest { 9 | 10 | public static void main(String[] args) { 11 | for (int i = 0; i < 20; i++) { 12 | new Thread(new Runnable() { 13 | public void run() { 14 | RedisConnection redisConnection = RedisConnectionUtil.create(); 15 | UUIDServiceRedisImpl uuidServiceRedis = new UUIDServiceRedisImpl(); 16 | uuidServiceRedis.setRedisConnection(redisConnection); 17 | uuidServiceRedis.setDbIndex(15); 18 | try { 19 | for (int i = 0; i < 100; i++) { 20 | System.out.println(new Date() + " get uuid = " + uuidServiceRedis.fetchUUID("MEMBER", 8, Boolean.TRUE) + " by member in " + Thread.currentThread().getName()); 21 | } 22 | } catch (Exception e) { 23 | e.printStackTrace(); 24 | } 25 | } 26 | }).start(); 27 | 28 | new Thread(new Runnable() { 29 | public void run() { 30 | RedisConnection redisConnection = RedisConnectionUtil.create(); 31 | UUIDServiceRedisImpl uuidServiceRedis = new UUIDServiceRedisImpl(); 32 | uuidServiceRedis.setRedisConnection(redisConnection); 33 | uuidServiceRedis.setDbIndex(15); 34 | try { 35 | for (int i = 0; i < 100; i++) { 36 | System.out.println(new Date() + " get uuid = " + uuidServiceRedis.fetchDailyUUID("ORDER", 8, Boolean.TRUE) + " by order in " + Thread.currentThread().getName()); 37 | } 38 | } catch (Exception e) { 39 | e.printStackTrace(); 40 | } 41 | } 42 | }).start(); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/RedisCacheTest.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import com.x9710.common.redis.impl.CacheServiceRedisImpl; 5 | import com.x9710.common.redis.test.domain.Student; 6 | import org.junit.Assert; 7 | import org.junit.Before; 8 | import org.junit.Test; 9 | 10 | /** 11 | * 缓存服务测试类 12 | * 13 | * @author 杨高超 14 | * @since 2017-12-09 15 | */ 16 | public class RedisCacheTest { 17 | private CacheServiceRedisImpl cacheService; 18 | 19 | @Before 20 | public void before() { 21 | RedisConnection redisConnection = RedisConnectionUtil.create(); 22 | cacheService = new CacheServiceRedisImpl(); 23 | cacheService.setDbIndex(2); 24 | cacheService.setRedisConnection(redisConnection); 25 | } 26 | 27 | @Test 28 | public void testStringCache() { 29 | String key = "name"; 30 | String value = "grace"; 31 | cacheService.putObject(key, value); 32 | String cachValue = (String) cacheService.pullObject(key); 33 | //检查从缓存中获取的字符串是否等于原始的字符串 34 | Assert.assertTrue(value.equals(cachValue)); 35 | //检查从缓存删除已有对象是否返回 true 36 | Assert.assertTrue(cacheService.delObject(key)); 37 | //检查从缓存删除已有对象是否返回 false 38 | Assert.assertFalse(cacheService.delObject(key + "1")); 39 | //检查从缓存获取已删除对象是否返回 null 40 | Assert.assertTrue(cacheService.pullObject(key) == null); 41 | } 42 | 43 | 44 | @Test 45 | public void testObjectCache() { 46 | Student oriStudent = new Student(); 47 | oriStudent.setId("2938470s9d8f0"); 48 | oriStudent.setName("柳白猿"); 49 | oriStudent.setAge(36); 50 | cacheService.putObject(oriStudent.getId(), oriStudent); 51 | Student cacheStudent = (Student) cacheService.pullObject(oriStudent.getId()); 52 | Assert.assertTrue(oriStudent.equals(cacheStudent)); 53 | Assert.assertTrue(cacheService.delObject(oriStudent.getId())); 54 | Assert.assertTrue(cacheService.pullObject(oriStudent.getId()) == null); 55 | } 56 | 57 | @Test 58 | public void testExpireCache() { 59 | String key = "name"; 60 | String value = "grace"; 61 | cacheService.putObject(key, value); 62 | cacheService.expire(key, 300); 63 | String cachValue = (String) cacheService.pullObject(key); 64 | Assert.assertTrue(value.equals(cachValue)); 65 | Long ttl = cacheService.ttl(key); 66 | Assert.assertTrue(ttl > 250 && ttl <= 300); 67 | Assert.assertTrue(value.equals(cachValue)); 68 | Assert.assertTrue(cacheService.delObject(key)); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/impl/UUIDServiceRedisImpl.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.impl; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import com.x9710.common.redis.UUIDService; 5 | import redis.clients.jedis.Jedis; 6 | 7 | import java.text.DateFormat; 8 | import java.text.NumberFormat; 9 | import java.text.SimpleDateFormat; 10 | import java.util.Calendar; 11 | import java.util.GregorianCalendar; 12 | 13 | /** 14 | * @author 杨高超 15 | * @since 2017-11-19 16 | */ 17 | public class UUIDServiceRedisImpl implements UUIDService { 18 | private RedisConnection redisConnection; 19 | private Integer dbIndex; 20 | 21 | private DateFormat df = new SimpleDateFormat("yyyyMMdd"); 22 | 23 | public void setRedisConnection(RedisConnection redisConnection) { 24 | this.redisConnection = redisConnection; 25 | } 26 | 27 | public void setDbIndex(Integer dbIndex) { 28 | this.dbIndex = dbIndex; 29 | } 30 | 31 | public Long fetchDailyUUID(String key, Integer length, Boolean haveDay) { 32 | Jedis jedis = null; 33 | try { 34 | jedis = redisConnection.getJedis(); 35 | jedis.select(dbIndex); 36 | Calendar now = new GregorianCalendar(); 37 | String day = df.format(now.getTime()); 38 | key = key + "_" + day; 39 | Long num = jedis.incr(key); 40 | //设置 key 过期时间 41 | if (num == 1) { 42 | jedis.expire(key, (24 - now.get(Calendar.HOUR_OF_DAY)) * 3600 + 1800); 43 | } 44 | if (haveDay) { 45 | return createUUID(num, day, length); 46 | } else { 47 | return num; 48 | } 49 | } finally { 50 | if (jedis != null) { 51 | jedis.close(); 52 | } 53 | } 54 | } 55 | 56 | public Long fetchUUID(String key, Integer length, Boolean haveDay) { 57 | Jedis jedis = null; 58 | try { 59 | jedis = redisConnection.getJedis(); 60 | jedis.select(dbIndex); 61 | Calendar now = new GregorianCalendar(); 62 | Long num = jedis.incr(key); 63 | 64 | if (haveDay) { 65 | String day = df.format(now.getTime()); 66 | return createUUID(num, day, length); 67 | } else { 68 | return num; 69 | } 70 | } finally { 71 | if (jedis != null) { 72 | jedis.close(); 73 | } 74 | } 75 | } 76 | 77 | private Long createUUID(Long num, String day, Integer length) { 78 | String id = String.valueOf(num); 79 | if (id.length() < length) { 80 | NumberFormat nf = NumberFormat.getInstance(); 81 | nf.setGroupingUsed(false); 82 | nf.setMaximumIntegerDigits(length); 83 | nf.setMinimumIntegerDigits(length); 84 | id = nf.format(num); 85 | } 86 | return Long.parseLong(day + id); 87 | } 88 | 89 | } 90 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/impl/LBSServiceRedisImpl.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.impl; 2 | 3 | import com.x9710.common.redis.LBSService; 4 | import com.x9710.common.redis.RedisConnection; 5 | import com.x9710.common.redis.domain.GeoCoordinate; 6 | import com.x9710.common.redis.domain.Postion; 7 | import redis.clients.jedis.GeoRadiusResponse; 8 | import redis.clients.jedis.GeoUnit; 9 | import redis.clients.jedis.Jedis; 10 | import redis.clients.jedis.params.geo.GeoRadiusParam; 11 | 12 | import java.util.ArrayList; 13 | import java.util.List; 14 | 15 | /** 16 | * 位置服务实现类 17 | * 18 | * @author 杨高超 19 | * @since 2017-12-26 20 | */ 21 | public class LBSServiceRedisImpl implements LBSService { 22 | private RedisConnection redisConnection; 23 | 24 | private Integer dbIndex; 25 | 26 | public void setRedisConnection(RedisConnection redisConnection) { 27 | this.redisConnection = redisConnection; 28 | } 29 | 30 | public void setDbIndex(Integer dbIndex) { 31 | this.dbIndex = dbIndex; 32 | } 33 | 34 | public boolean addPostion(Postion postion) { 35 | Jedis jedis = redisConnection.getJedis(); 36 | try { 37 | return (1L == jedis.geoadd(postion.getType(), 38 | postion.getCoordinate().getLongitude(), 39 | postion.getCoordinate().getLatitude(), 40 | postion.getId())); 41 | } finally { 42 | if (jedis != null) { 43 | jedis.close(); 44 | } 45 | } 46 | } 47 | 48 | public List radious(String type, GeoCoordinate center, Long distinct, Boolean asc) { 49 | List postions = new ArrayList(); 50 | Jedis jedis = redisConnection.getJedis(); 51 | try { 52 | GeoRadiusParam geoRadiusParam = GeoRadiusParam.geoRadiusParam().withCoord().withDist(); 53 | if (asc) { 54 | geoRadiusParam.sortAscending(); 55 | } else { 56 | geoRadiusParam.sortDescending(); 57 | } 58 | List responses = jedis.georadius(type, 59 | center.getLongitude(), 60 | center.getLatitude(), 61 | distinct.doubleValue(), 62 | GeoUnit.M, 63 | geoRadiusParam); 64 | if (responses != null) { 65 | for (GeoRadiusResponse response : responses) { 66 | Postion postion = new Postion(response.getMemberByString(), 67 | type, 68 | response.getCoordinate().getLongitude(), 69 | response.getCoordinate().getLatitude()); 70 | postion.setDistinct(response.getDistance()); 71 | postions.add(postion); 72 | } 73 | } 74 | } finally { 75 | if (jedis != null) { 76 | jedis.close(); 77 | } 78 | } 79 | 80 | return postions; 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /src/test/java/com/x9710/common/redis/test/RedisLBSTest.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.test; 2 | 3 | import com.x9710.common.redis.RedisConnection; 4 | import com.x9710.common.redis.domain.GeoCoordinate; 5 | import com.x9710.common.redis.domain.Postion; 6 | import com.x9710.common.redis.impl.CacheServiceRedisImpl; 7 | import com.x9710.common.redis.impl.LBSServiceRedisImpl; 8 | import org.junit.Assert; 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | 12 | import java.util.List; 13 | 14 | /** 15 | * LBS服务测试类 16 | * 17 | * @author 杨高超 18 | * @since 2017-12-28 19 | */ 20 | public class RedisLBSTest { 21 | private CacheServiceRedisImpl cacheService; 22 | private LBSServiceRedisImpl lbsServiceRedis; 23 | private String type = "SHOP"; 24 | private GeoCoordinate center; 25 | 26 | @Before 27 | public void before() { 28 | RedisConnection redisConnection = RedisConnectionUtil.create(); 29 | lbsServiceRedis = new LBSServiceRedisImpl(); 30 | lbsServiceRedis.setDbIndex(15); 31 | lbsServiceRedis.setRedisConnection(redisConnection); 32 | Postion postion = new Postion("2017122801", type, 91.118970, 29.654210); 33 | lbsServiceRedis.addPostion(postion); 34 | postion = new Postion("2017122802", type, 116.373472, 39.972528); 35 | lbsServiceRedis.addPostion(postion); 36 | postion = new Postion("2017122803", type, 116.344820, 39.948420); 37 | lbsServiceRedis.addPostion(postion); 38 | postion = new Postion("2017122804", type, 116.637920, 39.905460); 39 | lbsServiceRedis.addPostion(postion); 40 | postion = new Postion("2017122805", type, 118.514590, 37.448150); 41 | lbsServiceRedis.addPostion(postion); 42 | postion = new Postion("2017122806", type, 116.374766, 40.109508); 43 | lbsServiceRedis.addPostion(postion); 44 | center = new GeoCoordinate(); 45 | center.setLongitude(116.373472); 46 | center.setLatitude(39.972528); 47 | } 48 | 49 | @Test 50 | public void test10KMRadious() { 51 | List postions = lbsServiceRedis.radious(type, center, 1000 * 10L, true); 52 | Assert.assertTrue(postions.size() == 2 && exist(postions, "2017122802") && exist(postions, "2017122803")); 53 | } 54 | 55 | @Test 56 | public void test50KMRadious() { 57 | List postions = lbsServiceRedis.radious(type, center, 1000 * 50L, true); 58 | Assert.assertTrue(postions.size() == 4 59 | && exist(postions, "2017122802") 60 | && exist(postions, "2017122803") 61 | && exist(postions, "2017122806") 62 | && exist(postions, "2017122804")); 63 | } 64 | 65 | private boolean exist(List postions, String key) { 66 | if (postions != null) { 67 | for (Postion postion : postions) { 68 | if (postion.getId().equals(key)) { 69 | return true; 70 | } 71 | } 72 | } 73 | return false; 74 | } 75 | 76 | @Before 77 | public void after() { 78 | RedisConnection redisConnection = RedisConnectionUtil.create(); 79 | cacheService = new CacheServiceRedisImpl(); 80 | cacheService.setDbIndex(15); 81 | cacheService.setRedisConnection(redisConnection); 82 | cacheService.delObject(type); 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/impl/LockServiceRedisImpl.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.impl; 2 | 3 | import com.x9710.common.redis.LockService; 4 | import com.x9710.common.redis.RedisConnection; 5 | import org.apache.commons.logging.Log; 6 | import org.apache.commons.logging.LogFactory; 7 | import redis.clients.jedis.Jedis; 8 | 9 | import java.text.DateFormat; 10 | import java.text.SimpleDateFormat; 11 | import java.util.Collections; 12 | import java.util.Date; 13 | import java.util.UUID; 14 | 15 | /** 16 | * 分布式锁 redis 实现 17 | * 18 | * @author 杨高超 19 | * @since 2017-12-14 20 | */ 21 | public class LockServiceRedisImpl implements LockService { 22 | 23 | private static Log log = LogFactory.getLog(LockServiceRedisImpl.class); 24 | 25 | private static String SET_SUCCESS = "OK"; 26 | 27 | private static String KEY_PRE = "REDIS_LOCK_"; 28 | 29 | private DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS"); 30 | 31 | private RedisConnection redisConnection; 32 | 33 | private Integer dbIndex; 34 | 35 | private Integer lockExpirseTime; 36 | 37 | private Integer tryExpirseTime; 38 | 39 | public void setRedisConnection(RedisConnection redisConnection) { 40 | this.redisConnection = redisConnection; 41 | } 42 | 43 | public void setDbIndex(Integer dbIndex) { 44 | this.dbIndex = dbIndex; 45 | } 46 | 47 | public void setLockExpirseTime(Integer lockExpirseTime) { 48 | this.lockExpirseTime = lockExpirseTime; 49 | } 50 | 51 | public void setTryExpirseTime(Integer tryExpirseTime) { 52 | this.tryExpirseTime = tryExpirseTime; 53 | } 54 | 55 | public String lock(String key) { 56 | Jedis jedis = null; 57 | try { 58 | jedis = redisConnection.getJedis(); 59 | jedis.select(dbIndex); 60 | key = KEY_PRE + key; 61 | String value = fetchLockValue(); 62 | if (SET_SUCCESS.equals(jedis.set(key, value, "NX", "EX", lockExpirseTime))) { 63 | log.debug("Reids Lock key : " + key + ",value : " + value); 64 | return value; 65 | } 66 | } catch (Exception e) { 67 | e.printStackTrace(); 68 | } finally { 69 | if (jedis != null) { 70 | jedis.close(); 71 | } 72 | } 73 | return null; 74 | } 75 | 76 | public String tryLock(String key) { 77 | 78 | Jedis jedis = null; 79 | try { 80 | jedis = redisConnection.getJedis(); 81 | jedis.select(dbIndex); 82 | key = KEY_PRE + key; 83 | String value = fetchLockValue(); 84 | Long firstTryTime = new Date().getTime(); 85 | do { 86 | if (SET_SUCCESS.equals(jedis.set(key, value, "NX", "EX", lockExpirseTime))) { 87 | log.debug("Reids Lock key : " + key + ",value : " + value); 88 | return value; 89 | } 90 | log.info("Redis lock failure,waiting try next"); 91 | try { 92 | Thread.sleep(100); 93 | } catch (InterruptedException e) { 94 | e.printStackTrace(); 95 | } 96 | } while ((new Date().getTime() - tryExpirseTime * 1000) < firstTryTime); 97 | } catch (Exception e) { 98 | e.printStackTrace(); 99 | } finally { 100 | if (jedis != null) { 101 | jedis.close(); 102 | } 103 | } 104 | return null; 105 | } 106 | 107 | public boolean unLock(String key, String value) { 108 | Long RELEASE_SUCCESS = 1L; 109 | Jedis jedis = null; 110 | try { 111 | jedis = redisConnection.getJedis(); 112 | jedis.select(dbIndex); 113 | key = KEY_PRE + key; 114 | String command = "if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end"; 115 | if (RELEASE_SUCCESS.equals(jedis.eval(command, Collections.singletonList(key), Collections.singletonList(value)))) { 116 | return true; 117 | } 118 | } catch (Exception e) { 119 | e.printStackTrace(); 120 | } finally { 121 | if (jedis != null) { 122 | jedis.close(); 123 | } 124 | } 125 | return false; 126 | } 127 | 128 | /** 129 | * 生成加锁的唯一字符串 130 | * 131 | * @return 唯一字符串 132 | */ 133 | private String fetchLockValue() { 134 | return UUID.randomUUID().toString() + "_" + df.format(new Date()); 135 | } 136 | } 137 | -------------------------------------------------------------------------------- /src/main/java/com/x9710/common/redis/impl/CacheServiceRedisImpl.java: -------------------------------------------------------------------------------- 1 | package com.x9710.common.redis.impl; 2 | 3 | import com.x9710.common.redis.CacheService; 4 | import com.x9710.common.redis.RedisConnection; 5 | import com.x9710.common.redis.SerializeUtil; 6 | import org.apache.commons.logging.Log; 7 | import org.apache.commons.logging.LogFactory; 8 | import redis.clients.jedis.Jedis; 9 | 10 | /** 11 | * 缓存服务 redis 实现类 12 | * 13 | * @author 杨高超 14 | * @since 2017-12-09 15 | */ 16 | public class CacheServiceRedisImpl implements CacheService { 17 | private static Log log = LogFactory.getLog(CacheServiceRedisImpl.class); 18 | 19 | private RedisConnection redisConnection; 20 | 21 | private Integer dbIndex; 22 | 23 | public void setRedisConnection(RedisConnection redisConnection) { 24 | this.redisConnection = redisConnection; 25 | } 26 | 27 | public void setDbIndex(Integer dbIndex) { 28 | this.dbIndex = dbIndex; 29 | } 30 | 31 | public void putObject(String key, Object value) { 32 | putObject(key, value, -1); 33 | } 34 | 35 | public void putObject(String key, Object value, int expiration) { 36 | 37 | Jedis jedis = null; 38 | try { 39 | jedis = redisConnection.getJedis(); 40 | jedis.select(dbIndex); 41 | if (expiration > 0) { 42 | jedis.setex(key.getBytes(), expiration, SerializeUtil.serialize(value)); 43 | } else { 44 | jedis.set(key.getBytes(), SerializeUtil.serialize(value)); 45 | } 46 | } catch (Exception e) { 47 | log.warn(e.getMessage(), e); 48 | } finally { 49 | if (jedis != null) { 50 | jedis.close(); 51 | } 52 | } 53 | } 54 | 55 | public Object pullObject(String key) { 56 | 57 | log.trace("strar find cache with " + key); 58 | Jedis jedis = null; 59 | try { 60 | jedis = redisConnection.getJedis(); 61 | jedis.select(dbIndex); 62 | byte[] result = jedis.get(key.getBytes()); 63 | if (result == null) { 64 | log.trace("can not find caceh with " + key); 65 | return null; 66 | } else { 67 | log.trace("find cache success with " + key); 68 | return SerializeUtil.unserialize(result); 69 | } 70 | } catch (Exception e) { 71 | log.warn(e.getMessage(), e); 72 | } finally { 73 | if (jedis != null) { 74 | jedis.close(); 75 | } 76 | } 77 | 78 | return null; 79 | } 80 | 81 | public boolean expire(String key, int expireSecond) { 82 | log.trace("strar set expire " + key); 83 | Jedis jedis = null; 84 | try { 85 | jedis = redisConnection.getJedis(); 86 | jedis.select(dbIndex); 87 | return jedis.expire(key, expireSecond) == 1; 88 | } catch (Exception e) { 89 | log.warn(e.getMessage(), e); 90 | } finally { 91 | if (jedis != null) { 92 | jedis.close(); 93 | } 94 | } 95 | return false; 96 | } 97 | 98 | public Long ttl(String key) { 99 | log.trace("get set expire " + key); 100 | Jedis jedis = null; 101 | try { 102 | jedis = redisConnection.getJedis(); 103 | jedis.select(dbIndex); 104 | return jedis.ttl(key); 105 | } catch (Exception e) { 106 | log.warn(e.getMessage(), e); 107 | } finally { 108 | if (jedis != null) { 109 | jedis.close(); 110 | } 111 | } 112 | return -2L; 113 | } 114 | 115 | public boolean delObject(String key) { 116 | log.trace("strar delete cache with " + key); 117 | Jedis jedis = null; 118 | try { 119 | jedis = redisConnection.getJedis(); 120 | jedis.select(dbIndex); 121 | return jedis.del(key.getBytes()) > 0; 122 | } catch (Exception e) { 123 | log.warn(e.getMessage(), e); 124 | } finally { 125 | if (jedis != null) { 126 | jedis.close(); 127 | } 128 | } 129 | 130 | return false; 131 | } 132 | 133 | public void clearObject() { 134 | 135 | Jedis jedis = null; 136 | try { 137 | jedis = redisConnection.getJedis(); 138 | jedis.select(dbIndex); 139 | jedis.flushDB(); 140 | } catch (Exception e) { 141 | log.warn(e.getMessage(), e); 142 | } finally { 143 | if (jedis != null) { 144 | jedis.close(); 145 | } 146 | } 147 | } 148 | } 149 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------