前不久分享過Redis的基本數據結構及基本命令詳解。在熟悉了redis的基本操做以後(若是還有對redis的基本操做不熟悉的,能夠點擊前面的鏈接先熟悉下),今天給你們分享下實際開發中對redis操做的Java實現版本。java
使用maven來構建項目在當下應該已是主流了,因此咱們也不例外使用了Maven。由於使用了spring對redis封裝的jar,因此也須要引入spring基本jar,Maven依賴以下:正則表達式
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.1.5.RELEASE</version> </dependency> <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.1.3.RELEASE</version> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.2</version> </dependency> <dependency> <groupId></groupId> <artifactId>redis</artifactId> </dependency>
實現代碼篇幅有點長,並且segmentfault代碼div的高度有限制,建議你們把代碼拷貝到開發工具中再閱讀。redis
package spring.redis; import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.stereotype.Service; import java.io.UnsupportedEncodingException; import java.util.*; import java.util.stream.Collectors; @Service public class SpringRedisHandler implements InitializingBean { //redis編碼 private static final String redisCode = "utf-8"; private static final String EmptyString = ""; @Autowired private RedisTemplate<String, String> jtRedis; /** * 設置key-value【不含超時時間】 * * @param key * @param value */ public void set(String key, Object value) { this.set(key, String.valueOf(value), 0L); } /** * 設置key-value【含超時時間】 * * @param key * @param value * @param liveTime */ public void set(String key, Object value, long liveTime) { this.set(key.getBytes(), String.valueOf(value).getBytes(), liveTime); } @SuppressWarnings({"unchecked", "rawtypes"}) private void set(final byte[] key, final byte[] value, final long liveTime) { jtRedis.execute(new RedisCallback() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { connection.set(key, value); if (liveTime > 0) { connection.expire(key, liveTime); } return 1L; } }); } /** * get key的值 * * @param key * @return */ public String get(final String key) { return jtRedis.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { try { return new String(connection.get(key.getBytes()), redisCode); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } } }); } /** * 是否存在key * * @param key * @return */ public boolean exists(final String key) { return jtRedis.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { return connection.exists(key.getBytes()); } }); } /** * 某數據中全部key的總數 * * @return */ public long dbSize() { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.dbSize(); } }); } /** * 檢測redis服務器是否能平通 */ public String ping() { return jtRedis.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { return connection.ping(); } }); } /** * value增長某個值 * * @param key * @param value * @return */ public Long incr(String key, long value) { return incr(key.getBytes(), value); } private Long incr(byte[] key, long value) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.incrBy(key, value); } }); } /** * 自增 * * @param key * @return */ public Long incr(String key) { return incr(key.getBytes(), 1); } /** * 自減 * * @param key * @return */ public Long decr(String key) { return decr(key.getBytes(), 1); } /** * value減小某個值 * * @param key * @param value * @return */ public Long decr(String key, long value) { return decr(key.getBytes(), value); } private Long decr(byte[] key, long value) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.decrBy(key, value); } }); } /** * 刪除key * * @param key * @return */ public Long del(String key) { return del(key.getBytes()); } private Long del(byte[] key) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.del(key); } }); } /** * flushdb:刪除db下的全部數據 */ @SuppressWarnings({"rawtypes", "unchecked"}) public void flushDb() { jtRedis.execute(new RedisCallback() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); return 1L; } }); } /** * 設置hash * * @param key * @param field * @param value * @return */ public Boolean hSet(String key, String field, String value) { return jtRedis.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException { return redisConnection.hSet(key.getBytes(), field.getBytes(), value.getBytes()); } }); } /** * 獲取hash的屬性值 * * @param key * @param field * @return */ public String hGet(String key, String field) { return jtRedis.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection redisConnection) throws DataAccessException { return new String(redisConnection.hGet(key.getBytes(), field.getBytes())); } }); } /** * 批量設置hash * * @param key * @param values */ public void hMSet(String key, Map<String, Object> values) { jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection redisConnection) throws DataAccessException { redisConnection.hMSet(key.getBytes(), stringObjectMapToBytes(values)); return null; } }); } /** * 批量獲取hash的多個屬性 * * @param key * @param fields * @return */ public List<String> hMGet(String key, String... fields) { return jtRedis.execute(new RedisCallback<List<String>>() { @Override public List<String> doInRedis(RedisConnection redisConnection) throws DataAccessException { List<String> listFileds = new ArrayList<>(); for (int i = 0; i < fields.length; i++) { listFileds.add(fields[i]); } List<byte[]> byteFileds = stringListToByte(listFileds); return bytesListToString(redisConnection.hMGet(key.getBytes(), byteFileds.toArray(new byte[byteFileds.size()][byteFileds.size()]))); } }); } /** * 獲取hash的全部屬性 * * @param key * @return */ public Map<String, String> hGetAll(String key) { return jtRedis.execute(new RedisCallback<Map<String, String>>() { @Override public Map<String, String> doInRedis(RedisConnection redisConnection) throws DataAccessException { return bytesMapToString(redisConnection.hGetAll(key.getBytes())); } }); } /** * 針對hash中某個屬性增長指定的值 * * @param key * @param field * @param value * @return */ public Double hIncrBy(String key, String field, double value) { return jtRedis.execute(new RedisCallback<Double>() { @Override public Double doInRedis(RedisConnection redisConnection) throws DataAccessException { return redisConnection.hIncrBy(key.getBytes(), field.getBytes(), value); } }); } /** * hash是存在某屬性 * * @param key * @param field * @return */ public Boolean hExists(String key, String field) { return jtRedis.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException { return redisConnection.hExists(key.getBytes(), field.getBytes()); } }); } /** * 刪除hash的某屬性 * * @param key * @param field * @return */ public Long hDel(String key, String field) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection redisConnection) throws DataAccessException { return redisConnection.hDel(key.getBytes(), field.getBytes()); } }); } /** * 向zset中的某個key添加一個屬性幾分數(能夠根據分數排序) * * @param key * @param score * @param field * @return */ public Boolean zAdd(String key, double score, String field) { return jtRedis.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection redisConnection) throws DataAccessException { return redisConnection.zAdd(key.getBytes(), score, field.getBytes()); } }); } /** * 給zset中的某個key中的某個屬性增長指定分數 * * @param key * @param score * @param field * @return */ public Double zIncrBy(String key, double score, String field) { return jtRedis.execute(new RedisCallback<Double>() { @Override public Double doInRedis(RedisConnection redisConnection) throws DataAccessException { return redisConnection.zIncrBy(key.getBytes(), score, field.getBytes()); } }); } /** * 從list左側插入一個元素 * * @param key * @param values * @return */ public Long lPush(String key, String value) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.lPush(key.getBytes(), value.getBytes()); } }); } /** * 從list左側插入多個元素 * * @param key * @param values * @return */ public Long lPush(String key, List<String> values) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { List<byte[]> bytes = stringListToByte(values); return connection.lPush(key.getBytes(), bytes.toArray(new byte[bytes.size()][bytes.size()])); } }); } /** * 從list的左側取出一個元素 * * @param key * @return */ public String lPop(String key) { return jtRedis.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { if (connection.lLen(key.getBytes()) > 0) { return new String(connection.lPop(key.getBytes())); } else { return EmptyString; } } }); } /** * 向list的右側插入一個元素 * * @param key * @param value * @return */ public Long rPush(String key, String value) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.rPush(key.getBytes(), value.getBytes()); } }); } /** * list的rpush,從右側插入多個元素 * * @param key * @param values * @return */ public Long rPush(String key, List<String> values) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { List<byte[]> bytes = stringListToByte(values); return connection.rPush(key.getBytes(), bytes.toArray(new byte[bytes.size()][bytes.size()])); } }); } /** * 從list的右側取出一個元素 * * @param key * @return */ public String rPop(String key) { return jtRedis.execute(new RedisCallback<String>() { @Override public String doInRedis(RedisConnection connection) throws DataAccessException { if (connection.lLen(key.getBytes()) > 0) { return new String(connection.rPop(key.getBytes())); } else { return EmptyString; } } }); } /** * 給set中添加元素 * * @param key * @param values * @return */ public Long sadd(String key, List<String> values) { return jtRedis.execute(new RedisCallback<Long>() { @Override public Long doInRedis(RedisConnection connection) throws DataAccessException { List<byte[]> bytes = stringListToByte(values); return connection.sAdd(key.getBytes(), bytes.toArray(new byte[bytes.size()][bytes.size()])); } }); } /** * 獲取set中的全部元素 * * @param key * @return */ public List<String> smembers(String key) { return jtRedis.execute(new RedisCallback<List<String>>() { @Override public List<String> doInRedis(RedisConnection connection) throws DataAccessException { return bytesListToString(connection.sMembers(key.getBytes())); } }); } /** * set中是否包含某元素 * * @param key * @param value * @return */ public Boolean sIsMember(String key, String value) { return jtRedis.execute(new RedisCallback<Boolean>() { @Override public Boolean doInRedis(RedisConnection connection) throws DataAccessException { return connection.sIsMember(key.getBytes(), value.getBytes()); } }); } private byte[][] change(List<byte[]> values) { byte[][] result = {}; return result; } private List<byte[]> stringListToByte(List<String> values) { return values .stream() .map(p -> p.getBytes()) .collect( Collectors.toList() ); } private List<String> bytesListToString(Collection<byte[]> values) { return values .stream() .map(p -> new String(p)) .collect( Collectors.toList() ); } private Map<String, String> bytesMapToString(Map<byte[], byte[]> values) { Map<String, String> result = new HashMap<>(); values.forEach((k, v) -> result.put(new String(k), new String(v))); return result; } private Map<byte[], byte[]> stringObjectMapToBytes(Map<String, Object> values) { Map<byte[], byte[]> result = new HashMap<>(); values.forEach((k, v) -> result.put(k.getBytes(), String.valueOf(v).getBytes())); return result; } /** * 正則表達式獲取值 * * @param pattern * @return */ public Set<String> keys(String pattern) { return jtRedis.keys(pattern); } @Override public void afterPropertiesSet() throws Exception { RedisSerializer<String> stringSerializer = new StringRedisSerializer(); jtRedis.setKeySerializer(stringSerializer); jtRedis.setValueSerializer(stringSerializer); jtRedis.setHashKeySerializer(stringSerializer); jtRedis.setHashValueSerializer(stringSerializer); } }
配置文件主要有兩個,一個是spirng相關配置的配置文件applicationContext-redis.xml,還有一個是redis相關配置文件redis-config.properties
applicationContext-redis.xml配置文件內容以下:spring
<?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: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-4.0.xsd"> <context:component-scan base-package="spring.redis"></context:component-scan> <!-- 加載redis配置文件 --> <context:property-placeholder location="classpath:redis-config.properties"/> <!-- 實例化redis配置 --> <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig"> <property name="maxIdle" value="${redis.maxIdle}"/> <property name="maxWaitMillis" value="${redis.maxWait}"/> <property name="testOnBorrow" value="${redis.testOnBorrow}"/> </bean> <!--redis鏈接工廠--> <bean id="dsRedis" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"> <property name="hostName" value="${redis.host}"/> <property name="port" value="${redis.port}"/> <property name="password" value="${redis.pass}"/> <property name="database" value="${redis.database}"/> <property name="poolConfig" ref="poolConfig"/> </bean> <bean id="jtRedis" class="org.springframework.data.redis.core.RedisTemplate"> <property name="connectionFactory" ref="dsRedis"/> </bean> </beans>
redis-config.properties配置文件內容以下:數據庫
#裝有redis數據庫的虛擬機中的一臺機器的ip redis.host=127.0.0.1 redis.port=6379 redis.pass= #默認存儲在databse[0]數據庫, redis的database至關於一個數據,默認也是0 redis.database=0 #maxIdle:最大空閒數 redis.maxIdle=300 #maxWait:最大等待時長,3秒 redis.maxWait=3000 #testOnBorrow:在提取一個jedis實例時,是否提早進行驗證操做;若是爲true,則獲得的jedis實例均是可用的; redis.testOnBorrow=true
雖然代碼篇幅有點長,可是都是基於spring封裝以後的再次封裝,你們應該都能理解。而且以上方法我都有測試過,親測可用,由於測試代碼也比較的簡單,所以就不貼出來了。最後,歡迎你們補充、批評、指正。