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);
}
}

 相关文章:https://my.oschina.net/u/3266761/blog/3023454

https://www.cnblogs.com/sxdcgaq8080/p/10949727.html

或者api2:

public String tsetRedis(){
2 Long time = System.currentTimeMillis();
3 for (int i = 0; i < 10000; i++) {
4 stringRedisTemplate.opsForValue().set("yi" + i, "wo" + i);
5 }
6 Long time1 = System.currentTimeMillis();
7 System.out.println("耗时:" + (time1 - time));
8 long time4 = System.currentTimeMillis();
9 stringRedisTemplate.executePipelined(new SessionCallback<Object>() {
10 @Override
11 public <K, V> Object execute(RedisOperations<K, V> redisOperations) throws DataAccessException {
12 for (int i = 0; i < 10000; i++) {
13 stringRedisTemplate.opsForValue().set("qiang" + i, "wo" + i);
14 }
15 return null; //RedisTemplate执行executePipelined方法是有返回值的
16 }
17 });
18 Long time2 = System.currentTimeMillis();
19 System.out.println("耗时:" + (time2 - time4));
20 return "redis正常耗时:" + (time1 - time) + "<br/>" + "redis管道耗时:" + (time2 - time4);
21 }

redis管道技术pipeline二——api的更多相关文章

  1. redis 管道技术 pipeline 简介

    redis数据库的主要瓶颈是网络速度,其次是内存与cpu.在应用允许的情况下,优先使用pipeline批量操作.pipeline批量发出请求/一次性获取响应:不是发出多个请求,每个请求都阻塞等待响应, ...

  2. Redis 管道技术

    Redis是一种基于客户端-服务端模型以及请求/响应协议的TCP服务.这意味着通常情况下一个请求会遵循以下步骤: 客户端向服务端发送一个查询请求,并监听Socket返回,通常是以阻塞模式,等待服务端响 ...

  3. redis管道技术

    1.redis管道pipeline解决的问题: 由于redis通信是通过tcp协议基础,并且是堵塞的处理方式,在第一个请求没有执行并返回前,无法处理第二个请求.所以事件浪费在了网络传输和堵塞请求中. ...

  4. Redis 管道(pipeline)

  5. Redis 管道pipeline

    Redis是一个cs模式的tcp server,使用和http类似的请求响应协议. 一个client可以通过一个socket连接发起多个请求命令. 每个请求命令发出后client通常会阻塞并等待red ...

  6. Redis 数据备份与恢复,安全,性能测试,客户端连接,管道技术,分区(四)

    Redis 数据备份与恢复 Redis SAVE 命令用于创建当前数据库的备份. 语法 redis Save 命令基本语法如下: redis 127.0.0.1:6379> SAVE 实例 re ...

  7. 缓存数据库-redis(管道)

    一:Redis 管道技术 Redis是一种基于客户端-服务端模型以及请求/响应协议的TCP服务.这意味着通常情况下一个请求会遵循以下步骤: 客户端向服务端发送一个查询请求,并监听Socket返回,通常 ...

  8. Redis学习篇(十二)之管道技术

    通过管道技术降低往返时延 当后一条命令不依赖于前一条命令的返回结果时,可以使用管道技术将多条命令一起 发送给redis服务器,服务器执行结束之后,一起返回结果,降低了通信频度.

  9. .NET客户端实现Redis中的管道(PipeLine)与事物(Transactions)

    序言 Redis中的管道(PipeLine)特性:简述一下就是,Redis如何从客户端一次发送多个命令,服务端到客户端如何一次性响应多个命令. Redis使用的是客户端-服务器模型和请求/响应协议的T ...

  10. Redis 新特性---pipeline(管道)

    转载自http://weipengfei.blog.51cto.com/1511707/1215042 Redis本身是一个cs模式的tcp server, client可以通过一个socket连续发 ...

随机推荐

  1. K8s 多租户方案的挑战与价值

    在当今企业环境中,随着业务的快速增长和多样化,服务器和云资源的管理会越来越让人头疼.K8s 虽然很强大,但在处理多个部门或团队的业务部署需求时,如果缺乏有效的多租户支持,在效率和资源管理方面都会不尽如 ...

  2. Head First Java学习:第十一章-异常处理

    第十一章 异常处理 1.方法可以抓住其他方法所抛出的异常:异常总是丢回给调用方 有风险.会抛出异常的程序代码: 负责声明异常:创建Exception对象并抛出 调用该方法的程序代码: 在try中调用程 ...

  3. PyTorch 实战(模型训练、模型加载、模型测试)

    本次将一个使用Pytorch的一个实战项目,记录流程:自定义数据集->数据加载->搭建神经网络->迁移学习->保存模型->加载模型->测试模型 自定义数据集 参考我 ...

  4. 15、string

    1.string是什么? Go中的字符串是一个字节的切片,可以通过将其内容封装起在""中来创建字符串.Go中的的字符串是Unicode兼容的并且是UTF-8编码的. 2.strin ...

  5. C++ Qt开发:TreeWidget 树形选择组件

    Qt 是一个跨平台C++图形界面开发库,利用Qt可以快速开发跨平台窗体应用程序,在Qt中我们可以通过拖拽的方式将不同组件放到指定的位置,实现图形化开发极大的方便了开发效率,本章将重点介绍TreeWid ...

  6. 深入理解 Docker 核心原理:Namespace、Cgroups 和 Rootfs

    通过这篇文章你可以了解到 Docker 容器的核心实现原理,包括 Namespace.Cgroups.Rootfs 等三个核心功能. 如果你对云原生技术充满好奇,想要深入了解更多相关的文章和资讯,欢迎 ...

  7. React 类组件转换为函数式

    函数式的 React 组件更加现代,并支持有用的 hooks,现在流行把旧式的类组件转换为函数式组件.这篇文章总结了转换的一些通用的步骤和陷阱. 通用替换 定义 从 class (\w+) exten ...

  8. IDEA插件(2 高效开发)

    一.高效开发代码插件 ① .TONGYI Lingma(阿里通灵代码AI插件) 提问回答 右键其他功能,只需要登录阿里账号就可以使用 ②.Talk X(AI提示插件,和阿里通灵代码很像的功能) ③.A ...

  9. 春秋云镜 - CVE-2022-32991

    靶标介绍: 该CMS的welcome.php中存在SQL注入攻击. 访问页面,先注册,使用邮箱加密码登录. bp抓包,后台挂上sqlipy然后去测welcome.php,常用的语句都没成功但过一会就有 ...

  10. Android开发之账号密码登录跳转、固定时间显示进度条实现

    登陆界面.登陆跳转和进度条功能实现 首先打开Android studio新建一个空项目,打开layout文件夹下的activity_main.xml文件,来设置登陆界面的布局.登陆界面需要两个输入框, ...