1,redis的监控信息通过客户端info命令就可以获取出来
2,redis的监控信息通过java代码获取使用JedisPool获取
代码如下:
RedisConfig:
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.timeout}")
private int timeout;
@Value("${spring.redis.password}")
private String password;
@Bean
public JedisPool redisPoolFactory() {
Logger.getLogger(getClass()).info("JedisPool注入成功!!");
Logger.getLogger(getClass()).info("redis地址:" + host + ":" + port);
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
JedisPool jedisPool = new JedisPool(jedisPoolConfig, host, port, timeout,password);
return jedisPool;
}
}
@Component
public class JedisUtil {
@Autowired
JedisPool jedisPool;
// 获取redis 服务器信息
public String getRedisInfo() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
Client client = jedis.getClient();
client.info();
String info = client.getBulkReply();
return info;
}catch (Exception e) {
e.printStackTrace();
}
finally {
// 返还到连接池
jedis.close();
}
return null;
}
// 获取日志列表
public List getLogs(long entries) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
List logList = jedis.slowlogGet(entries);
return logList;
} finally {
// 返还到连接池
jedis.close();
}
}
// 获取日志条数
public Long getLogsLen() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
long logLen = jedis.slowlogLen();
return logLen;
} finally {
// 返还到连接池
jedis.close();
}
}
// 清空日志
public String logEmpty() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.slowlogReset();
} finally {
// 返还到连接池
jedis.close();
}
}
// 获取占用内存大小
public Long dbSize() {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
// TODO 配置redis服务信息
Client client = jedis.getClient();
client.dbSize();
return client.getIntegerReply();
} finally {
// 返还到连接池
jedis.close();
}
}
3,为获取出来的参数添加解释:
代码如下:
public class RedisInfoDetail {
private static Map map = new HashMap();
static {
map.put("redis_version", "Redis 服务器版本");
map.put("redis_git_sha1", "Git SHA1");
map.put("redis_git_dirty", "Git dirty flag");
map.put("os", "Redis 服务器的宿主操作系统");
map.put("redis_build_id", "Redis 构建ID");
map.put("redis_mode", "Redis启动模式:standalone、Sentinel、Cluster");
map.put("arch_bits", " 架构(32 或 64 位)");
map.put("multiplexing_api", "Redis 所使用的事件处理机制");
map.put("gcc_version", "编译 Redis 时所使用的 GCC 版本");
map.put("process_id", "服务器进程的 PID");
map.put("run_id", "Redis 服务器的随机标识符(用于 Sentinel 和集群)");
map.put("tcp_port", "TCP/IP 监听端口");
map.put("uptime_in_seconds", "自 Redis 服务器启动以来,经过的秒数");
map.put("uptime_in_days", "自 Redis 服务器启动以来,经过的天数");
map.put("hz", "redis内部调度(进行关闭timeout的客户端,删除过期key等等)频率");
map.put("configured_hz", "redis的配置状态频率");
map.put("executable", "服务器可执行文件的路径");
map.put("config_file", "启动 redis 配置文件");
map.put("lru_clock", " 以分钟为单位进行自增的时钟,用于 LRU 管理");
map.put("connected_clients", "已连接客户端的数量(不包括通过从属服务器连接的客户端)");
map.put("client_longest_output_list", "当前连接的客户端当中,最长的输出列表");
map.put("client_longest_input_buf", "当前连接的客户端当中,最大输入缓存");
map.put("blocked_clients", "正在等待阻塞命令(BLPOP、BRPOP、BRPOPLPUSH)的客户端的数量");
map.put("used_memory", "由 Redis 分配器分配的内存总量,以字节(byte)为单位");
map.put("used_memory_human", "以人类可读的格式返回 Redis 分配的内存总量");
map.put("used_memory_rss", "从操作系统的角度,返回 Redis 已分配的内存总量(俗称常驻集大小)。这个值和 top 、 ps 等命令的输出一致");
map.put("used_memory_rss_human", "以可读的格式,操作系统角度,返回 redis 分配的内存总量");
map.put("used_memory_peak", " Redis 的内存消耗峰值(以字节为单位)");
map.put("used_memory_peak_human", "以人类可读的格式返回 Redis 的内存消耗峰值");
map.put("total_system_memory", "主机拥有的内存总量");
map.put("total_system_memory_human", "以可读的格式返回主机拥有的内存总量");
map.put("used_memory_lua", "Lua 引擎所使用的内存大小(以字节为单位)");
map.put("used_memory_lua_human", "以可读的格式返回Lua引擎使用内存");
map.put("maxmemory_human", "以可读的格式返回Redis实例的最大内存配置");
map.put("maxmemory", "Redis实例的最大内存配置");
map.put("maxmemory_policy", "当达到maxmemory时的淘汰策略");
map.put("loading", "服务器是否正在载入持久化文件");
map.put("rdb_changes_since_last_save", "离最近一次成功生成rdb文件,写入命令的个数");
map.put("rdb_bgsave_in_progress", "服务器是否正在创建rdb文件");
map.put("rdb_last_save_time", "最近一次成功rdb文件的时间戳");
map.put("rdb_last_bgsave_status", "最近一次成功rdb文件的状态");
map.put("rdb_last_bgsave_time_sec", "最近一次成功rdb文件的耗时");
map.put("rdb_current_bgsave_time_sec", "若当前正在创建rdb文件,指当前的创建操作已经耗费的时间");
map.put("aof_enabled", "aof是否开启");
map.put("aof_rewrite_in_progress", "aof的rewrite操作是否在进行中");
map.put("aof_last_cow_size", "上一次AOF保存操作期间写时复制的大小(以字节为单位)");
map.put("rdb_last_cow_size", "上一次RBD保存操作期间写时复制的大小(以字节为单位)");
map.put("lazyfree_pending_objects", "等待释放的对象数(由于使用ASYNC选项调用UNLINK或FLUSHDB和FLUSHALL)");
map.put("active_defrag_running", "碎片整理是否处于活动状态");
map.put("mem_aof_buffer", "aof时,占用的缓冲");
map.put("mem_allocator", "内存分配器(在编译时选择)");
map.put("mem_clients_normal", "Redis的客户端主的分配信息量");
map.put("mem_clients_slaves", "Redis的客户端从的分配信息量");
map.put("mem_replication_backlog", "Redis的内存复制积压分配信息量");
map.put("mem_not_counted_for_evict", "被驱逐的大小");
map.put("mem_fragmentation_bytes", "内存碎片的大小(以字节为单位)");
map.put("mem_fragmentation_ratio", "内存碎片率,used_memory_rss 和 used_memory 之间的比率");
map.put("rss_overhead_ratio", "常驻内存开销比例");
map.put("allocator_rss_bytes", "分配器的常驻内存大小(以字节为单位)");
map.put("allocator_rss_ratio", "分配器常驻内存比例");
map.put("allocator_frag_bytes", "分配器的碎片大小(以字节为单位)");
map.put("allocator_frag_ratio", "分配器的碎片率");
map.put("allocator_resident", "分配器常驻的内存");
map.put("allocator_active", "分配器活跃的内存");
map.put("allocator_allocated", "分配器分配的内存");
map.put("used_memory_dataset_perc", "used_memory_dataset在净内存(used_memory-used_memory_startup)使用量中所占的百分比");
map.put("used_memory_dataset", "数据集的大小(以字节为单位,used_memory - used_memory_overhead)");
map.put("number_of_cached_scripts", "Redis缓存脚本的数量");
map.put("used_memory_startup", "启动时消耗的初始内存量(以字节为单位)");
map.put("used_memory_overhead", "数据集的大小(以字节为单位,used_memory - used_memory_overhead)");
map.put("used_memory_peak_perc", "used_memory_peak在used_memory中所占的百分比");
map.put("client_recent_max_output_buffer", "当前连接的客户端当中,最长的输出列表");
map.put("client_recent_max_input_buffer", "当前连接的客户端当中,最大输入缓存");
map.put("atomicvar_api", "Atomicvar API");
map.put("used_memory_scripts_human", "人类使用过的记忆脚本");
map.put("used_memory_scripts", "Redis使用的内存脚本");
map.put("rss_overhead_bytes", "常驻内存开销大小(以字节为单位)");
map.put("aof_rewrite_scheduled", "rewrite任务计划,当客户端发送bgrewriteaof指令,如果当前rewrite子进程正在执行,那么将客户端请求的bgrewriteaof变为计划任务,待aof子进程结束后执行rewrite");
map.put("aof_last_rewrite_time_sec", "最近一次aof rewrite耗费时长");
map.put("aof_current_rewrite_time_sec", "若当前正在执行aof rewrite,指当前的已经耗费的时间");
map.put("aof_last_bgrewrite_status", "最近一次aof bgrewrite的状态");
map.put("aof_last_write_status", "最近一次aof写入状态");
map.put("aof_current_size", "aof文件当前大小");
map.put("aof_pending_rewrite", "rewrite任务计划,当客户端发送bgrewriteaof指令,如果当前rewrite子进程正在执行,那么将客户端请求的bgrewriteaof变为计划任务,待aof子进程结束后执行rewrite");
map.put("aof_buffer_length", "aof 缓冲区的大小");
map.put("aof_rewrite_buffer_length", "aof 重写缓冲区的大小");
map.put("aof_pending_bio_fsync", "后台IO队列中,等待fsync任务的个数");
map.put("aof_delayed_fsync", "被延迟的 fsync 调用数量");
map.put("total_connections_received", "自启动起连接过的总数。如果连接过多,说明短连接严重或连接池使用有问题,需调研代码的连接设置");
map.put("total_commands_processed", "自启动起运行命令的总数");
map.put("instantaneous_ops_per_sec", "每秒执行的命令数,相当于QPS");
map.put("total_net_input_bytes", "网络入口流量字节数");
map.put("total_net_output_bytes", "网络出口流量字节数");
map.put("instantaneous_input_kbps", "网络入口kps");
map.put("instantaneous_output_kbps", "网络出口kps");
map.put("rejected_connections", "拒绝的连接个数,由于maxclients限制,拒绝新连接的个数");
map.put("sync_full", "主从完全同步成功次数");
map.put("sync_partial_ok", "主从部分同步成功次数");
map.put("sync_partial_err", "主从部分同步失败次数");
map.put("expired_keys", "自启动起过期的key的总数");
map.put("evicted_keys", "使用内存大于maxmemory后,淘汰的key的总数");
map.put("expired_stale_perc", "过期的比率");
map.put("expired_time_cap_reached_count", "过期计数");
map.put("keyspace_hits", "在main dictionary字典中成功查到的key个数");
map.put("keyspace_misses","同上,未命中的key的个数");
map.put("pubsub_channels","发布/订阅频道数");
map.put("pubsub_patterns","发布/订阅模式数");
map.put("latest_fork_usec","上次的fork操作使用的时间(单位ms)");
map.put("migrate_cached_sockets","是否已经缓存了到该地址的连接");
map.put("slave_expires_tracked_keys","从实例到期key数量");
map.put("active_defrag_hits","主动碎片整理命中次数");
map.put("active_defrag_misses","主动碎片整理未命中次数");
map.put("active_defrag_key_hits","主动碎片整理key命中次数");
map.put("active_defrag_key_misses","主动碎片整理key未命中次数");
map.put("role","当前实例的角色master还是slave");
map.put("connected_slaves","slave的数量");
map.put("master_replid","主实例启动随机字符串");
map.put("master_replid2","主实例启动随机字符串2");
map.put("slave0","slave机器的信息、状态");
map.put("master_repl_offset","主从同步偏移量,此值如果和上面的offset相同说明主从一致没延迟,与master_replid可被用来标识主实例复制流中的位置。");
map.put("second_repl_offset","主从同步偏移量2,此值如果和上面的offset相同说明主从一致没延迟");
map.put("repl_backlog_size","复制缓冲区大小");
map.put("repl_backlog_first_byte_offset","复制缓冲区里偏移量的大小");
map.put("repl_backlog_histlen","此值等于 master_repl_offset - repl_backlog_first_byte_offset,该值不会超过repl_backlog_size的大小");
map.put("repl_backlog_active","复制缓冲区是否开启");
map.put("used_cpu_sys","Redis 服务器耗费的系统 CPU");
map.put("used_cpu_user","Redis 服务器耗费的用户 CPU");
map.put("used_cpu_sys_children","后台进程的核心态cpu使用率");
map.put("used_cpu_user_children","后台进程的用户态cpu使用率");
map.put("cluster_enabled","例是否启用集群模式");
// map.put("db.*","各个数据库(0-15)的 key 的数量,带有生存期的 key 的数量,平均存活时间");
map.put("Keyspace","redis的Keyspace_db0值");
}
private String key;
private String value;
private String desctiption;
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
this.desctiption = map.get(this.key);
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getDesctiption() {
return desctiption;
}
public void setDesctiption(String desctiption) {
this.desctiption = desctiption;
}
@Override
public String toString() {
return "RedisInfoDetail [key=" + key + ", value=" + value
+ ", desctiption=" + desctiption + "]";
}
}
4,redis的慢日志查询
代码如下:
public class Operate {
private long id;//slowlog唯一编号id
private String executeTime;// 查询的时间戳
private String usedTime;// 查询的耗时(微妙),如表示本条命令查询耗时47微秒
private String args;// 查询命令,完整命令为 SLOWLOG GET,slowlog最多保存前面的31个key和128字符
public Operate() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getExecuteTime() {
return executeTime;
}
public void setExecuteTime(String executeTime) {
this.executeTime = executeTime;
}
public String getUsedTime() {
return usedTime;
}
public void setUsedTime(String usedTime) {
this.usedTime = usedTime;
}
public String getArgs() {
return args;
}
public void setArgs(String args) {
this.args = args;
}
}
5,redis的监控信息的实现
代码如下:
RedisMonitoringInfoService:
public interface RedisMonitoringInfo {
/**
* @return 监控页面数据
*/
Map getMonitoringInfo();
}
RedisMonitoringService:
public interface RedisMonitoring {
/**
* @param qps 进程数
* @param time 页面差值
* @return
*/
//监控页面动态图形数据
Map getMonitoring(Integer qps, Integer time);
}
public interface RedisIdService {
public List
6,监控信息的实现
代码如下:
RedisMonitoringInfoServiceImpl:
@Service
public class RedisMonitoringInfoServiceImpl implements RedisMonitoringInfoService {
@Autowired
private RedisIdService redisService;
@Override
public Map getMonitoringInfo() {
Map map = new HashMap<>();
Integer dbId = redisService.getDbId();
String processId = redisService.getProcessId();
String usedMemory = redisService.getUsedMemory();
String connectedClients = redisService.getConnectedClients();
String hitProbability = redisService.getHitProbability();
map.put("processId", processId);
map.put("hitProbability", hitProbability);
map.put("connectedClients", connectedClients);
map.put("keysSize", dbId);
map.put("usedMemory", usedMemory+"M");
return map;
}
}
RedisMonitoringServiceImpl:
@Service
public class RedisMonitoringServiceImpl implements RedisMonitoringService {
@Autowired
private RedisIdService redisService;
@Autowired
private RedisUtil redisUtils;
@Override
public Map getMonitoring(Integer qps, Integer time) {
SimpleDateFormat sdf =new SimpleDateFormat("HH:mm:ss" );
Map item = new HashMap();
List> arrayList = new ArrayList>();
String usedMemory = redisService.getUsedMemory();
String usedCpuSys = redisService.getUsedCpuSys();
String usedMemoryRss = redisService.getUsedMemoryRss();
Double dbSizeQps = redisService.getDbSizeQps(qps, time);
Map memeryInfomap = new HashMap();
memeryInfomap.put("usedMemoryRss",usedMemoryRss);
memeryInfomap.put("usedMemory",usedMemory+"M");
item.put("dbSizeQps",dbSizeQps);
item.put("memeryInfomap",memeryInfomap);
item.put("usedCpuSys", usedCpuSys);
Date d= new Date();
String str = sdf.format(d);
item.put("date",str);
// String key = "redis_id";
// boolean redis = redisUtils.hasKey(key);
// List list = new ArrayList();
// SimpleDateFormat sdf =new SimpleDateFormat("HH:mm:ss" );
// if (!redis){
// Map item = new HashMap();
// for (Integer i = 0; i <= 20; i++) {
// item.put("dbSizeQps",null);
// item.put("memeryInfomap",null);
// item.put("usedCpuSys", null);
// Date d= new Date();
// String str = sdf.format(d);
// item.put("date",null);
// System.out.println("item" + item);
// list.add(item);
// }
// }else {
// list = (List)redisUtils.get(key);
// list.remove(0);
// Map item = new HashMap();
// List arrayList = new ArrayList();
// String usedMemory = redisService.getUsedMemory();
// String usedCpuSys = redisService.getUsedCpuSys();
// String usedMemoryRss = redisService.getUsedMemoryRss();
// Double dbSizeQps = redisService.getDbSizeQps(qps, time);
// Map memeryInfomap = new HashMap();
// memeryInfomap.put("usedMemoryRss",usedMemoryRss);
// memeryInfomap.put("usedMemory",usedMemory);
// item.put("dbSizeQps",dbSizeQps);
// item.put("memeryInfomap",memeryInfomap);
// item.put("usedCpuSys", usedCpuSys);
// Date d= new Date();
// String str = sdf.format(d);
// item.put("date",str);
// System.out.println("item" + item);
//
// list.add(item);
// }
// redisUtils.set(key, list);
// List> list1 = new ArrayList>();
// Map map = new HashMap<>();
// String usedMemory = redisService.getUsedMemory();
// String usedCpuSys = redisService.getUsedCpuSys();
// String usedMemoryRss = redisService.getUsedMemoryRss();
// Double dbSizeQps = redisService.getDbSizeQps(qps, time);
// map.put("usedCpuSys", usedCpuSys);
// map.put("usedMemoryRss",usedMemoryRss);
// list1.add(map);
// Map item = new HashMap();
// Map memeryInfomap = new HashMap();
// memeryInfomap.put("usedMemoryRss",usedMemoryRss);
// memeryInfomap.put("usedMemory",usedMemory);
// List list = new ArrayList();
//
// SimpleDateFormat sdf =new SimpleDateFormat("HH:mm:ss" );
// for (Integer i = 1; i <= 21; i++) {
//
// //place here
//
// item.put("dbSizeQps",dbSizeQps);
// item.put("memeryInfomap",memeryInfomap);
// item.put("usedCpuSys", usedCpuSys);
// Date d= new Date();
// String str = sdf.format(d);
// item.put("date",str);
// System.out.println("item" + item);
//
// list.add(item);
// }
// String usedMemory = redisService.getUsedMemory();
// String usedCpuSys = redisService.getUsedCpuSys();
// String usedMemoryRss = redisService.getUsedMemoryRss();
// Double dbSizeQps = redisService.getDbSizeQps(qps, time);
// Map memeryInfomap = new HashMap();
// memeryInfomap.put("usedMemoryRss",usedMemoryRss);
// memeryInfomap.put("usedMemory",usedMemory);
// List list = new ArrayList();
// SimpleDateFormat sdf =new SimpleDateFormat("HH:mm:ss" );
// Boolean result = false;
// int count = 0;
// Map item = new HashMap();
// while(!result) {
// try {
// Thread.sleep(10 * 1000); //设置暂停的时间 10 秒
// count ++ ;
// item.put("dbSizeQps",dbSizeQps);
// item.put("memeryInfomap",memeryInfomap);
// item.put("usedCpuSys", usedCpuSys );
// String format = sdf.format(new Date());
// item.put("date", format);
// System.out.println("item" + item);
// System.out.println(sdf.format(new Date()) + "--循环执行第" + count + "次");
// if (count == 21) {
// result = true;
// break ;
// }
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// list.add(item);
// }
// if(list.size()==20) {
// list.remove(0);
// list.add()
// }
return item;
}
}
@Service
public class RedisIdServiceImpl implements RedisIdService {
protected static Logger LOGGER = LoggerFactory.getLogger(RedisIdServiceImpl.class);
@Autowired
JedisUtil redisUtil;
@Autowired
private RedisTemplate redisTemplate;
@Autowired
private RedisConnectMapper mapper;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisUtil redisUtils;
public List> getRedisInfo() {
//获取redis服务器信息
String info = redisUtil.getRedisInfo();
List> ridList = new ArrayList>();
String[] strs = info.split("\n");
RedisInfoDetail rif = null;
if (strs != null && strs.length > 0) {
for (int i = 0; i < strs.length; i++) {
Map map = new HashMap();
rif = new RedisInfoDetail();
String s = strs[i];
String[] str = s.split(":");
if (str != null && str.length > 1) {
String key = str[0];
String value = str[1];
// String desctiption = str[2];
map.put("key", key);
map.put("value", value);
rif.setKey(key);
String desctiption = rif.getDesctiption();
map.put("desctiption", desctiption);
// rif.setKey(key);
// rif.setValue(value);
ridList.add(map);
}
}
}
return ridList;
}
/**
* @param qps
* @param time
* @return
*/
//获取qps参数
@Override
public Double getDbSizeQps(Integer qps, Integer time) {
Double process = null;
Double qpsTime = null;
// Double qps = null;
// //获取redis服务器信息
// String info = redisUtil.getRedisInfo();
// List> ridList = new ArrayList>();
// String[] strs = info.split("\n");
// RedisInfoDetail rif = null;
// if (strs != null && strs.length > 0) {
// for (int i = 0; i < strs.length; i++) {
// Map map =new HashMap();
// rif = new RedisInfoDetail();
// String s = strs[i];
// String[] str = s.split(":");
// if (str != null && str.length > 1) {
// String key = str[0];
// System.out.println("[][][][]"+key.length());
// String value = str[1];
// System.out.println("[][][][]"+value.length());
// rif.setKey(key);
// String value1 = rif.getValue();
// process = (double) map.put("process_id", value1);
//
// qps = (process*0.8)/(24 * 3600 * 0.2);
// ridList.add(map);
// }
// }
// }
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("process_id")) {
process = Double.valueOf((detail[1].substring(0, detail[1].length() - 1)));
break;
}
}
if (process!=null){
qpsTime = (process - qps) / (time);
}
// qps = (process*0.8)/(qps * 3600 * 0.2);
return qpsTime;
}
//获取redis日志列表
public List getLogs(long entries) {
List list = redisUtil.getLogs(entries);
List opList = null;
Operate op = null;
boolean flag = false;
if (list != null && list.size() > 0) {
opList = new LinkedList();
for (Slowlog sl : list) {
String args = JSON.toJSONString(sl.getArgs());
if (args.equals("[\"PING\"]") || args.equals("[\"SLOWLOG\",\"get\"]") || args.equals("[\"DBSIZE\"]") || args.equals("[\"INFO\"]")) {
continue;
}
op = new Operate();
flag = true;
op.setId(sl.getId());
op.setExecuteTime(getDateStr(sl.getTimeStamp() * 1000));
op.setUsedTime(sl.getExecutionTime() / 1000.0 + "ms");
op.setArgs(args);
opList.add(op);
}
}
if (flag)
return opList;
else
return null;
}
//获取日志总数
public Long getLogLen() {
return redisUtil.getLogsLen();
}
//清空日志
public String logEmpty() {
return redisUtil.logEmpty();
}
//获取当前数据库中key的数量
public Map getKeysSize() {
long dbSize = redisUtil.dbSize();
Map map = new HashMap();
map.put("dbSize", dbSize);
return map;
}
//获取当前redis使用内存大小情况
public Map getMemeryInfo() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("used_memory")) {
map = new HashMap();
map.put("used_memory", detail[1].substring(0, detail[1].length() - 1));
map.put("create_time", new Date().getTime());
break;
} else {
if (detail[0].equals("used_memory_rss")) {
map = new HashMap();
map.put("used_memory_rss", detail[1].substring(0, detail[1].length() - 1));
map.put("create_time", new Date().getTime());
break;
}
}
}
return map;
}
//获取当前redis使用内存大小情况
public Map getMemeryInfolist() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Long aLong1 = redisUtil.dbSize();
HttpServletRequest request = null;
List list = null;
Map map = null;
//判断前端请求资源
if (request != null) {
list = new LinkedList<>();
if (list != null && list.size() > 0) {
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("used_memory")) {
map = new HashMap();
map.put("used_memory", detail[1].substring(0, detail[1].length() - 1));
map.put("create_time", new Date().getTime());
break;
}
}
}
list.add(map);
if (list.size() < 20) {
return (Map) list;
}
return null;
} else {
return null;
}
}
//获取内存大小
@Override
public String getUsedMemory() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("used_memory")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
//比率
@Override
public String getMemFragmentationRatio() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("mem_fragmentation_ratio")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
@Override
public String getUsedCpuSys() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("used_cpu_sys")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
@Override
public String getUsedCpuUserChildren() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("used_cpu_user_children")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
//命中
@Override
public String getTotalConnectionsReceived() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("total_connections_received")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
@Override
public String getUsedMemoryRss() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("used_memory_rss")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
@Override
public String getConnectedClients() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("connected_clients")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
/**
* @return probability 缓存命中率
* keyspace_hits:命中的次数
* keyspace_misses:没有命中的次数
*/
//缓存命中概率
@Override
public String getHitProbability() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
Double memohitsry = null;
Double memorymisses = null;
Double probability = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("keyspace_hits")) {
memohitsry = Double.valueOf(detail[1].substring(0, detail[1].length() - 1));
System.out.println("keyspace_hits----=" + memohitsry);
} else if (detail[0].equals("keyspace_misses")) {
memorymisses = Double.valueOf(detail[1].substring(0, detail[1].length() - 1));
System.out.println("keyspace_misses=-------=" + memorymisses);
break;
}
}
if (memohitsry!=null&&memorymisses!=null){
probability = memohitsry / (memohitsry + memorymisses);
BigDecimal mData = new BigDecimal(probability).setScale(2, BigDecimal.ROUND_HALF_UP);
NumberFormat percent = NumberFormat.getPercentInstance();
percent.setMaximumFractionDigits(2);
return percent.format(mData.doubleValue());
}
return null;
}
@Override
public String getProcessId() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (String s : strs) {
String[] detail = s.split(":");
if (detail[0].equals("process_id")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
private Map getRedisInfo(String str){
//s:1\n a=2,B:W=1
Map result = new HashMap();
String [] arr = str.split("\n");
String [] istr;
String [] jsrt;
String [] jjstr;
for (int i = 0; i < arr.length; i++){
istr = arr[i].split(":");
if(istr.length >=2 ){
jsrt = istr[1].split(",");
if(jsrt.length >= 2){
for (int j=0; j < jsrt.length; j++){
jjstr = jsrt[j].split("=");
if(jjstr.length >= 2){
result.put(jjstr[0],jjstr[1]);
}
}
}else{
result.put(istr[0],istr[1]);
}
}
}
return result;
}
@Override
public Integer getDbId() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = new HashMap();
String[] split;
String[] dh;
String[] dd;
int sun =0;
int js = 0;
int zh = 0;
int ss = 0;
for (String s : strs) {
split = s.split(":");
for (int i = 0; i < 16; i++) {
if (split[0].equals("db" + i)) {
if (split.length >= 2) {
dh = split[1].split(",");
for (int j = 0; j < dh.length; j++) {
if (dh.length >= 2) {
dd = dh[j].split("=");
if (dd.length >= 2) {
if (dd[0].equals("keys")){
sun= Integer.parseInt(dd[1]);
zh += sun;
}
}
}
}
System.out.println(zh);
} else {
map.put(split[0], split[1]);
}
}
}
}
Object keys = map.get("keys");
System.out.println("----===="+keys);
//
// for (int i = 0; i < 16; i++) {
//
// keysh = info.get("db"+i);
// System.out.println(keysh);
// }
// String[] strs = redisUtil.getRedisInfo().split("\n");
// Map map = null;
// String[] memory = null;
// int key = Integer.parseInt(null);
// String[] split = null;
// String[] detail;
// String[] keys;
// String istr;
// String [] jsrt;
// String [] jjstr;
// Integer sun =null;
// Integer zh =null;
// Map result = new HashMap();
// for (String s : strs) {
// for (int i = 0; i < 16; i++) {
// detail = s.split(":");
// if (detail[0].equals("db"+i)) {
// detail[1].substring(0, detail[1].length()- 1);
// if (jsrt.length>2){
// jsrt = s.split(",");
// istr = detail[1].substring(0, jsrt[1].length() - 1);
// if (keys[0].equals("keys")) {
// keys = s.split("=");
// key = Integer.parseInt(keys[1].substring(0, keys[1].length() - 1));
// }
// }else{
// result.put(detail[0],jsrt[1]);
// }
// //String keys = "keys=1,expires=0,avg_ttl=0";
// break;
// }
// sun =key;
// zh = key+sun;
// }
//
// }
return zh;
}
@Override
public String getKeyspace() {
String[] strs = redisUtil.getRedisInfo().split("\n");
Map map = null;
String memory = null;
for (int i = 0; i < strs.length; i++) {
String s = strs[i];
String[] detail = s.split(":");
if (detail[0].equals("keyspace")) {
memory = detail[1].substring(0, detail[1].length() - 1);
System.out.println(memory);
break;
}
}
System.out.println();
return memory;
}
/**
* @param pageSize 当前页面 数据个数
* @param pageNumber 当前页面
* @param id 切换redis db库数据
* @param keysid 根据 keysid 查询单个
* @return
*/
@Override
public List> getAllRedisVal2(Integer pageSize, Integer pageNumber, Integer id, String keysid) {
LOGGER.info("======================开始 Redis查询数据======================");
Long startTime = System.nanoTime();
List> list = new ArrayList<>();
int startIndex = pageSize * (pageNumber - 1) + 1;
// String redis = redisUtil.get("redis", id);
String redisId = redisUtil.getRedisId(id);
System.out.println("redis" + redisId);
LOGGER.info("redis" + redisId);
LettuceConnectionFactory connectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
if (connectionFactory != null && id != connectionFactory.getDatabase()) {
LOGGER.info("当前所在的db=" + connectionFactory.getDatabase());
connectionFactory.setDatabase(id);
connectionFactory.afterPropertiesSet();
redisTemplate.setConnectionFactory(connectionFactory);
connectionFactory.resetConnection();
// redisTemplate.opsForValue().set("redistest", "测试切换");
// Object redisId1 = redisTemplate.opsForValue().get("redistest");
// LOGGER.info("-------------=="+(String) redisId1);
LOGGER.info("切换redisdb库成功当前所在的db=" + connectionFactory.getDatabase());
// System.out.println("-------------e" + e);
}
//使用scan的方法
Map result = (Map) redisTemplate.execute(new RedisCallback() {
/**
* @param redisConnection 连接redsi
* @return
* @throws DataAccessException
*/
@Nullable
@Override
public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
Cursor results = redisConnection.scan(new ScanOptions.ScanOptionsBuilder().match("*").build());
List keys = new LinkedList<>();
Map
7,RedisController , 这里的swagger,和分页方法是调用的封装的,需要自己添加
/*
*
@Api(tags = {"redis指标参数"})
@RestController
@RequestMapping("/redis")
public class RedisController extends BaseController {
@Autowired
private RedisIdService redisService;
@Autowired
private RedisMonitoring redisMonitoring;
@Autowired
private RedisMonitoringInfo redisMonitoringInfo;
@Autowired
private RedisConnectMapper mapper;
@GetMapping("/list")
public String getUserList() {
return "HELLO WORD";
}
/**
* @param model redis指标参数
* @throws IOException
*/
@GetMapping("redisMonitor")
@ApiOperation("getRedisInfo获取redis的info,getLogs获取redis的日志记录,getLogLen获取日志总数")
public void redisMonitor(Model model) throws IOException {
//获取redis的info
List> ridList = redisService.getRedisInfo();
//获取redis的日志记录
List logList = redisService.getLogs(100);
//获取日志总数
long logLen = redisService.getLogLen();
model.addAttribute("infoList", ridList);
model.addAttribute("logList", logList);
model.addAttribute("logLen", logLen);
Map map = new HashMap();
map.put("ridList", ridList);
PageInfo pageInfo = initPageInfo();
if (pageInfo == null) {
pageInfo = new PageInfo("items=0-9");
}
pageInfo.setCount(ridList.size());
ResponseUtil.toJSON(pageInfo, ridList.subList(pageInfo.getStart(), pageInfo.getEnd() + 1 > ridList.size() ? ridList.size() : pageInfo.getEnd() + 1));
// return nu;
}
/**
* @param qps 进程数量
* @param time 页面差值
* @return
*/
//获取当前数据库实施监控
@GetMapping("getMonitoring")
@ResponseBody
@ApiOperation("实施监控")
public Map getMonitoring(Integer qps, Integer time) {
Map map = new HashMap();
Map monitoring = redisMonitoring.getMonitoring(qps, time);
Map monitoringInfo = redisMonitoringInfo.getMonitoringInfo();
map.put("monitoring", monitoring);
map.put("monitoringInfo", monitoringInfo);
return map;
}
@GetMapping("getLogs")
@ResponseBody
@ApiOperation("实施监控")
public Map getLogs() {
Map map = new HashMap();
//获取redis的日志记录
List logList = redisService.getLogs(10);
//获取日志总数
long logLen = redisService.getLogLen();
map.put("logList",logList);
map.put("logLen",logLen);
return map;
}
//获取key值
@GetMapping(value = "getAllRedisVal2")
@ResponseBody
@ApiOperation("获取不同库的key值")
public void getRedisConnect(Integer pageSize, Integer pageNumber, Integer id, String key) throws IOException {
List> allRedisVal2 = redisService.getAllRedisVal2(pageSize, pageNumber, id, key);
System.out.println(allRedisVal2);
PageInfo pageInfo = initPageInfo();
if (pageInfo == null) {
pageInfo = new PageInfo("items=0-9");
}
if (allRedisVal2 != null & allRedisVal2.size() > 0) {
pageInfo.setCount(allRedisVal2.size());
System.out.println(allRedisVal2);
ResponseUtil.toJSON(pageInfo, allRedisVal2);
}else {
ResponseUtil.toJSON(pageInfo, 0);
}
}
/**
* @return 连接redis树形结构
*/
//切换redis的db库
@GetMapping(value = "getSwitchoverRedis")
@ResponseBody
@ApiOperation("切换redis的db库的树形")
public List> getSwitchoverRedis() {
List> redisConnect = mapper.getRedisConnect();
String dbNm = ObjectUtils.toString(redisConnect.get(0).get("DB_NM"));
List> list = new ArrayList>();
Map map = new HashMap();
// map.put("parent","01");
map.put("lvl", 1);
map.put("hasChiLdren", "true");
map.put("connectFlag", true);
map.put("children", "true");
map.put("name", dbNm);
map.put("exceptionFlag", "false");
map.put("id", "01");
list.add(map);
Map item =null;
for (Integer i = 0; i < 16; i++) {
item = new HashMap();
int[] arr1 = new int[] {i};
bubbleSort(arr1);
//place here
item.put("parent", "01");
item.put("lvl", 2);
item.put("hasChiLdren", "false");
item.put("connectFlag", true);
item.put("children", "false");
item.put("name", "db" + i);
item.put("exceptionFlag", "false");
item.put("id", i);
System.out.println("item" + item);
list.add(item);
}
redisService.getSwitchoverRedis();
return list;
}
public static void bubbleSort(int[] arr) {
for(int i = 0; i < arr.length-1; i++) {
for(int j = 0; j < arr.length - 1 - i; j++) {
if(arr[j] > arr[j + 1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
8,ResponseUtil
public abstract class ResponseUtil {
public static String FILEDOWNLOAD = "fileDownload";
public static String FILEUPLOAD = "fileUpload";
/**
* 往response中输出JSON格式内容
* @param req HttpServletRequest
* @param resp HttpServletResponse
* @param result 转换的对象
* @param status {@link HttpServletResponse}
* @throws IOException
*/
public static void toJSON(List> list, int status) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setStatus(status);
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setContentType(HttpConstants.CONTENT_TYPE_JSON);
//文件下载前台根据这个来判断是否启用回调函数。
Cookie cookie = new Cookie(FILEDOWNLOAD, "false");
cookie.setPath("/");
resp.addCookie(cookie);
String response = JSONUtil.stringify(list);
resp.getWriter().print(response);
}
public static void toJSON(Serializable bean, int status) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setStatus(status);
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setContentType(HttpConstants.CONTENT_TYPE_JSON);
String response = JSONUtil.stringify(bean);
resp.getWriter().print(response);
}
public static void toJSON(Object object, int status) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setStatus(status);
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setContentType(HttpConstants.CONTENT_TYPE_JSON);
String response = JSONUtil.stringify(object);
resp.getWriter().print(response);
}
/**
* 生成json字符串, 返回的浏览器状态默认为 {@link HttpServletResponse#SC_OK}
*
* @param object
* @param useUpperCaseKey true使用大写的key,false使用原来的key值
* @throws IOException
*/
public static void toJSON(Object object, boolean useUpperCaseKey) throws IOException{
toJSON(object, useUpperCaseKey, HttpServletResponse.SC_OK);
}
/**
* 生成json字符串
*
* @param object
* @param useUpperCaseKey true使用大写的key,false使用原来的key值
* @param status
* @throws IOException
*/
public static void toJSON(Object object, boolean useUpperCaseKey, int status) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setStatus(status);
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setContentType(HttpConstants.CONTENT_TYPE_JSON);
String response = JSONUtil.stringify(object, useUpperCaseKey);
resp.getWriter().print(response);
}
/**
* 生成json字符串
*
* @param object
* @param useUpperCaseKey true使用大写的key,false使用原来的key值
* @param status
* @param SerializerFeature 特征,如SerializerFeature.WriteMapNullValue表示保留map中空的数据
* @throws IOException
*/
public static void toJSON(Object object, boolean useUpperCaseKey, int status, SerializerFeature... features) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setStatus(status);
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setContentType(HttpConstants.CONTENT_TYPE_JSON);
String response = JSONUtil.stringify(object, useUpperCaseKey, features);
resp.getWriter().print(response);
}
/**
* 往response中输出JSON格式内容
* @param req HttpServletRequest
* @param resp HttpServletResponse
* @param result 转换的对象
* @throws IOException
*/
public static void toJSON(List> list) throws IOException{
toJSON(list, HttpServletResponse.SC_OK);
}
public static void toJSON(Serializable bean) throws IOException{
toJSON(bean, HttpServletResponse.SC_OK);
}
public static void toJSON(Object object) throws IOException{
toJSON(object, HttpServletResponse.SC_OK);
}
/**
* 往response中输出JSON格式内容
* @param req HttpServletRequest
* @param resp HttpServletResponse
* @param pageInfo 分页信息
* @param result 转换的对象
* @throws IOException
*/
public static void toJSON(PageInfo pageInfo, List> list) throws IOException{
HttpServletRequest req = ApplicationContextUtil.getServletActionContext().getRequest();
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
if(pageInfo != null){
resp.setHeader("Content-Range", pageInfo.toString());
}
String compKeysHeader = req.getHeader(HttpConstants.KEY_HEADER_COMP_KEYS); // 传过来的key,已都转换为大写
if(compKeysHeader != null){
String[] keys = compKeysHeader.split("&");
for(Map each : list){
StringBuilder sbPK = new StringBuilder();//使用&符号拼接
for(int i = 0; i < keys.length; i++){
if(i > 0){
sbPK.append("&");
}
String[] eachKeyMap = keys[i].split("=");
String mapKey = eachKeyMap[0];
String beanIdKey = eachKeyMap[1];
Object o = each.get(mapKey);
Assert.notNull(o, "主键的值不能为null");
String s = "";
if(o instanceof Date){
// 所有主键中的时间一律按照包含秒来处理,如果没有则设置为00秒
s = DateFormatUtils.format((Date)o, "yyyy-MM-dd HH:mm:ss");
}else{
s = o.toString();
}
sbPK.append(beanIdKey).append("=").append(s);
}
each.put(HttpConstants.KEY_BIZ_ID, sbPK.toString()); // 加载数据时使用
each.put(HttpConstants.KEY_ID, IdGenerator.UUID()); // 记录的唯一代理主键。如果本身就是一个代理主键,则不添加。
}
}
toJSON(list,HttpServletResponse.SC_OK);
}
/**
* 往response中输出html格式内容
* @param html html字符串对象
* @throws IOException
*/
public static void toHTML(String html) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
toHTML(resp, html, HttpServletResponse.SC_OK);
}
/**
* 往response中输出html格式内容
* @param req HttpServletRequest
* @param resp HttpServletResponse
* @param html 输出的html文本
* @throws IOException
*/
@Deprecated
public static void toHTML(HttpServletRequest req, HttpServletResponse resp, String html) throws IOException{
toHTML(req, resp, html, HttpServletResponse.SC_OK);
}
/**
* 往response中输出html格式内容(HttpServletRequest 不需要传入)
* @param req HttpServletRequest
* @param resp HttpServletResponse
* @param html 输出的html文本
* @param status {@link HttpServletResponse}
* @throws IOException
*/
@Deprecated
public static void toHTML(HttpServletRequest req, HttpServletResponse resp, String html, int status) throws IOException{
resp.setStatus(status);
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setContentType(HttpConstants.CONTENT_TYPE_HTML);
resp.getWriter().print(html);
}
/**
* 往response中输出html格式内容
* @param resp HttpServletResponse
* @param html 输出的html文本
* @param status {@link HttpServletResponse}
* @throws IOException
*/
public static void toHTML(HttpServletResponse resp, String html, int status) throws IOException{
resp.setStatus(status);
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setContentType(HttpConstants.CONTENT_TYPE_HTML);
resp.getWriter().print(html);
}
public static void toHTMLFile(HttpServletRequest req,
HttpServletResponse resp, String fileName) throws IOException {
InputStream io = req.getSession().getServletContext().getResourceAsStream(fileName);
if(io == null){
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}else{
resp.setStatus(HttpServletResponse.SC_OK);
resp.setHeader("Cache-Control", "no-cache"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setHeader("Cache-Control", "no-store"); //$NON-NLS-1$ //$NON-NLS-2$
resp.setContentType(HttpConstants.CONTENT_TYPE_HTML);
IOUtils.copy(io, resp.getOutputStream());
}
}
/**
* @Deprecated 请调用{@code ResponseUtil.showMessage()}
* @param js
* @throws IOException
*/
@Deprecated
public static void toJavaScript(String js) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write("");
}
/**
* 导出Excel文件
* @param req
* @param resp
* @param workbook POI的workbook
* @param fileName 导出文件的文件名
* @throws IOException
*/
public static void toExcel(HttpServletRequest req,
HttpServletResponse resp,
Workbook workbook,
String fileName) throws IOException{
resp.setContentType(HttpConstants.CONTENT_TYPE_EXCEL);
if (isIE()) {
fileName = URLEncoder.encode(fileName, "UTF8");
} else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
//文件下载前台根据这个来回调
Cookie cookie = new Cookie(FILEDOWNLOAD, "true");
cookie.setPath("/");
resp.addCookie(cookie);
resp.addHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream out = resp.getOutputStream();
workbook.write(out);
out.close();
}
private static boolean isIE(){
HttpServletRequest req = ApplicationContextUtil.getServletActionContext().getRequest();
Browser browser = Browser.parseUserAgentString(req.getHeader("User-Agent"));
String browserName = browser.getName();
if (browserName != null && browserName.startsWith("Internet Explorer")) {
return true;
}
return false;
}
/**
* 导出Excel文件,这里没有指定导出文件使用的文件名,使用workbook中的第一个工作簿名称作为导出文件的文件名。
* @param req
* @param resp
* @param workbook POI的workbook
* @throws IOException
*/
public static void toExcel(HttpServletRequest req,
HttpServletResponse resp,
Workbook workbook) throws IOException{
String fileName = workbook.getSheetName(0);
if(workbook instanceof HSSFWorkbook){
if(!fileName.endsWith(".xls")){
fileName += ".xls";
}
}else if(workbook instanceof XSSFWorkbook){
if(!fileName.endsWith(".xlsx")){
fileName += ".xlsx";
}
}
toExcel(req, resp, workbook, fileName);
}
/**
* 导出Word文件
* @param req
* @param resp
* @param word ooxml类型的word
* @param fileName 导出文件的文件名
* @throws IOException
*/
public static void toWord(HttpServletRequest req,
HttpServletResponse resp,
String word,
String fileName) throws IOException{
resp.setContentType(HttpConstants.CONTENT_TYPE_WORD);
//服务器端如何识别客户端浏览器是IE11的情况,IE7-10都通过USER-AGENT中的MSIE判断为IE浏览器
//IE11:User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
boolean isIE = isIE();
if (isIE) {
fileName = URLEncoder.encode(fileName, "UTF8");
} else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
//文件下载前台根据这个来回调
Cookie cookie = new Cookie(FILEDOWNLOAD, "true");
cookie.setPath("/");
resp.addCookie(cookie);
resp.addHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream out = resp.getOutputStream();
out.write(word.getBytes("UTF-8"));
out.close();
}
public static void showUploadSuccessMessage(String message) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
//文件下载前台根据这个来判断是否启用回调函数。
Cookie cookie = new Cookie(FILEUPLOAD, "true");
cookie.setPath("/");
resp.addCookie(cookie);
showUploadMessage("ok", message);
}
public static void showUploadErrorMessage(String message) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
//文件下载前台根据这个来判断是否启用回调函数。
Cookie cookie = new Cookie(FILEUPLOAD, "false");
cookie.setPath("/");
resp.addCookie(cookie);
showUploadMessage("error", message);
}
//上传失败后返回错误模板的下载地址
public static void showUploadErrorMessageForDownload(String url) throws IOException{
showUploadMessage("download", url, null);
}
//上传失败后返回错误模板的下载地址
public static void showUploadErrorMessageForDownload(String url, String message) throws IOException{
showUploadMessage("download", url, message);
}
//上传遇到重复数据提示是否覆盖,继续上传
public static void showUploadErrorMessageForReUpload(String url, String message) throws IOException{
showUploadMessage("reUpload", url, message);
}
private static void showUploadMessage(String status, String url, String message) throws IOException{
HttpServletRequest req = ApplicationContextUtil.getServletActionContext().getRequest();
String uploadType = req.getParameter("uploadType");
if(StringUtils.isBlank(uploadType)){
throw new IllegalArgumentException("不是有效的上传文件操作,uploadType的值不能为空");
}
Map map = new HashMap();
map.put("status", status);
map.put("message", message);
map.put("url", url);
if(StringUtils.isNotBlank(uploadType)){
toUpload(uploadType, map);
}
}
private static void showUploadMessage(String status, String message) throws IOException{
HttpServletRequest req = ApplicationContextUtil.getServletActionContext().getRequest();
String uploadType = req.getParameter("uploadType");
if(StringUtils.isBlank(uploadType)){
throw new IllegalArgumentException("不是有效的上传文件操作,uploadType的值不能为空");
}
// 使用iframe提交时,暂时没有找到传递sourceWidgetId的地方,改为不再传递,js中直接获取本地值。
Map map = new HashMap();
map.put("status", status);
map.put("message", message);
toUpload(uploadType, map);
}
public static void toUpload(String uploadType, Map result) throws IOException {
HttpServletRequest req = ApplicationContextUtil.getServletActionContext().getRequest();
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
if (uploadType.equals("html5")) {
ResponseUtil.toJSON(result);
}else if(uploadType.equals("flash")) {
}else if(uploadType.equals("iframe")) {
String html = "";
ResponseUtil.toHTML(req, resp, html);
}
}
/**
* 文件下载,需要手动设置content type,参考{@link HttpConstants}
* @param req
* @param resp
* @param bytes 文件字节数据组
* @param fileName 文件名称
* @throws IOException
*/
public static void toDownload(byte[] bytes, String fileName) throws IOException{
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
//服务器端如何识别客户端浏览器是IE11的情况,IE7-10都通过USER-AGENT中的MSIE判断为IE浏览器
//IE11:User-Agent Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
boolean isIE = isIE();
if (isIE) {
fileName = URLEncoder.encode(fileName, "UTF8");
} else {
fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
resp.addHeader("Content-Disposition", "attachment;filename=" + fileName);
//文件下载前台根据这个来回调
Cookie cookie = new Cookie(FILEDOWNLOAD, "true");
cookie.setPath("/");
resp.addCookie(cookie);
OutputStream out = resp.getOutputStream();
out.write(bytes);
out.close();
}
public static void showDownloadMessage(String message) throws Exception{
HttpServletRequest req = ApplicationContextUtil.getServletActionContext().getRequest();
if(RequestUtil.isAjax(req)){
throw new IllegalArgumentException("只允许下载请求调用");
}
String sourceWidgetId = req.getParameter("sourceWidgetId");
if(StringUtils.isBlank(sourceWidgetId)){
throw new IllegalArgumentException("下载操作必须传递sourceWidgetId参数,用来指明是哪个按钮触发的下载");
}
ResponseUtil.toJavaScript("parent.lianpuPage.showTooltip(\""+sourceWidgetId+"\", '提示', '"+message+"')");
}
public static void showMessage(String status, String message) throws IOException {
HttpServletRequest req = ApplicationContextUtil.getServletActionContext().getRequest();
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
String uploadType = req.getParameter("uploadType");
Map map = new HashMap();
map.put("messageType", status);
map.put("message", message);
if(uploadType != null){
if (uploadType.equals("html5")) {
ResponseUtil.toJSON(map);
}else if(uploadType.equals("flash")) {
}else if(uploadType.equals("iframe")) {
String js = "window.parent.lianpuPage.showMessage(\""+message+"\",\""+status+"\")";
String javaScript = "";
String html = "";
ResponseUtil.toHTML(req, resp, html);
}
}
else{//增删改查的showMessage都调用toJavaScript, 即使是ajxa请求,返回json格式数据,返回到前台解析也是会出错的,那就忽略ajax的区别。
ResponseUtil.toJavaScript("window.parent.lianpuPage.showMessage(\""+message+"\",\""+status+"\")");
}
}
/**
* 自定义提示 在页面顶部显示无干扰信息
* msg 弹出的显示信息
* status 弹出框类型 ("message", "warning", "error", "fatal")
* duration 间隔时间
*/
public static void showMessage(String status, String message, boolean duration) throws IOException {
if(duration){
ResponseUtil.toJavaScript("window.parent.lianpuPage.showTip(\""+status+"\",\""+message+"\")");
}else{
showMessage(status,message);
}
}
/**
* 文件预览,需要手动设置content type
* @param req
* @param resp
* @param bytes 文件字节数据组
* @param fileName 文件名称
* @throws IOException
*/
public static void toPreview(byte[] bytes, String fileName) throws IOException{
String contentType = null;
Path path = Paths.get(fileName);
try {
contentType = Files.probeContentType(path);
} catch (IOException e) {
e.printStackTrace();
}
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setContentType(contentType);
resp.addHeader("Content-Disposition", "inline;filename=" + fileName);
OutputStream out = resp.getOutputStream();
out.write(bytes);
out.flush();
out.close();
}
/**
* 返回分页信息
*/
public static void setHeaderPage(PageInfo pageInfo) {
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
if(pageInfo != null){
resp.setHeader("Content-Range", pageInfo.toString());
}
}
/**
* 封装需要返回的信息
* @param status 返回状态 ReturnStateEnum.SUCCESS.getValue()、 ReturnStateEnum.WARNING.getValue()
* @param message 提示信息
* @param datas 返回数据
* @return
*/
public static Map toMessage(String status, String message, Object datas){
Map returnMap = new HashMap();
returnMap.put(ReturnStateEnum.STATUS.getValue(), status);
returnMap.put(ReturnStateEnum.MESSAGE.getValue(), message);
returnMap.put(ReturnStateEnum.DATA.getValue(), datas);
return returnMap;
}
/**
* 封装成功返回信息
* @param message 提示信息
* @param datas 返回数据
* @return
*/
public static Map toSuccessMessage(String message, Object datas){
return toMessage(ReturnStateEnum.SUCCESS.getValue(), message, datas);
}
/**
* 封装警告返回信息
* @param message 提示信息
* @param datas 返回数据
* @return
*/
public static Map toWarningMessage(String message, Object datas){
return toMessage(ReturnStateEnum.WARNING.getValue(), message, datas);
}
/**
* 返回提示信息至前端
* @param status 返回状态 ReturnStateEnum.SUCCESS.getValue()、 ReturnStateEnum.WARNING.getValue()
* @param message 提示信息
* @param datas 返回数据
* @throws IOException
*/
public static void showMessage(String status, String message, Object datas) throws IOException {
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setContentType(HttpConstants.CONTENT_TYPE_JSON);
Map obj = toMessage(status, message, datas);
String response = JSONUtil.stringify(obj, false);
resp.getWriter().print(response);
}
/**
* 返回成功提示信息至前端
* @param message 提示信息
* @param datas 返回数据
* @throws IOException
*/
public static void showSuccessMessage(String message, Object datas) throws IOException {
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setContentType(HttpConstants.CONTENT_TYPE_JSON);
Map obj = toSuccessMessage(message, datas);
String response = JSONUtil.stringify(obj, false);
resp.getWriter().print(response);
}
/**
* 返回警告提示信息至前端
* @param message 提示信息
* @param datas 返回数据
* @throws IOException
*/
public static void showWarningMessage(String message, Object datas) throws IOException {
HttpServletResponse resp = ApplicationContextUtil.getServletActionContext().getResponse();
resp.setContentType(HttpConstants.CONTENT_TYPE_JSON);
Map obj = toWarningMessage(message, datas);
String response = JSONUtil.stringify(obj, false);
resp.getWriter().print(response);
}
}
8,PageInfo
public class PageInfo implements Serializable{
private static final long serialVersionUID = 6448266504259394345L;
private String name;//名称
private int start;// 开始记录数
private int end;// 结束记录数
private int count;//总记录数
private int tempStrat;
private int tempEnd;
private int tempCurrent;
private String dbType;
public String getDbType() {
return dbType;
}
public void setDbType(String dbType) {
this.dbType = dbType;
}
public PageInfo() {
}
// items=0-14
public PageInfo(String rangeText){
String[] keyValuePair = rangeText.split("=");
assert keyValuePair.length == 2:"range文本被拆分为两个字符串";
this.name = keyValuePair[0];
String[] nums = keyValuePair[1].split("-");
assert nums.length == 2:"拆分出起始和结束两个字符串";
this.start = Integer.valueOf(nums[0]);
this.end = Integer.valueOf(nums[1]);
this.tempStrat=start;
this.tempEnd=end;
}
//items=0-1/3
@Override
public String toString() {
if(StringUtils.isEmpty(dbType) || "mysql".equals(dbType)) {
this.end=tempEnd;
this.start=tempStrat;
}
return String.format("items %d-%d/%d", start,end,count);
}
public void setCount(int count) {
if(count == 0){
this.start = this.end = this.count = 0;
}else{
this.count = count;
}
}
public String getName() {
return name;
}
public int getStart() {
if(StringUtils.isEmpty(dbType) || "mysql".equals(dbType)) {
int temp=tempEnd+1-tempStrat;
if(start==0) {
this.start=1;
}else {
this.start=tempStrat/temp+1;
}
this.tempCurrent=this.start;
}else if("oracle".equals(dbType)){
//assert count >= 0:"开始索引应大于0";
//if(count==0)return start;
//if(start>=count)return count-1;
int temp=tempEnd+1-tempStrat;
if(start==0) {
this.start=1;
}else {
this.start=tempStrat/temp+1;
}
this.tempCurrent=this.start;
}
return start;
}
public int getEnd() {
if(StringUtils.isEmpty(dbType) || "mysql".equals(dbType)) {
if(tempCurrent==1) {
this.end=tempEnd+1;
}else {
this.end=tempEnd+1-tempStrat;
}
}else if("oracle".equals(dbType)){
if(tempCurrent==1) {
this.end=tempEnd+1;
}else {
this.end=tempEnd+1-tempStrat;
}
}
return end;
}
public int getCount() {
return count;
}
}
9,BaseController
@CrossOrigin
public abstract class BaseController implements Serializable {
private static final long serialVersionUID = -8488485078794117606L;
@Value("${DBType}")
private String dbType;
private static String[] HEADER_RANGES = {"Range", "range", "X-Range", "x-range"};
protected PageInfo initPageInfo() {
HttpServletRequest req = ApplicationContextUtil.getServletActionContext().getRequest();
String range = null;
for(String each : HEADER_RANGES){
range = req.getHeader(each);
if(range != null){
break;
}
}
if(range != null){
PageInfo pageInfo = new PageInfo(range);
pageInfo.setDbType(dbType);
return pageInfo;
}
return null;
}
}
package com.chinairi.common.utils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@Component
@SuppressWarnings({“rawtypes”,“unchecked”})
public final class RedisUtil {
@Autowired
private RedisTemplate redisTemplate;
/**
* 26
* 指定缓存失效时间
* 27
*
* @param key 键
* 28
* @param time 时间(秒)
* 29
* @return 30
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 44
* 根据key 获取过期时间
* 45
*
* @param key 键 不能为null
* 46
* @return 时间(秒) 返回0代表为永久有效
* 47
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 53
* 判断key是否存在
* 54
*
* @param key 键
* 55
* @return true 存在 false不存在
* 56
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 67
* 删除缓存
* 68
*
* @param key 可以传一个值 或多个
* 69
*/
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 83
* 普通缓存获取
* 84
*
* @param key 键
* 85
* @return 值
* 86
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 92
* 普通缓存放入
* 93
*
* @param key 键
* 94
* @param value 值
* 95
* @return true成功 false失败
* 96
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 109
* 普通缓存放入并设置时间
* 110
*
* @param key 键
* 111
* @param value 值
* 112
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* 113
* @return true成功 false 失败
* 114
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 130
* 递增
* 131
*
* @param key 键
* 132
* @param delta 要增加几(大于0)
* 133
* @return 134
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 143
* 递减
* 144
*
* @param key 键
* 145
* @param delta 要减少几(小于0)
* 146
* @return 147
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* 157
* HashGet
* 158
*
* @param key 键 不能为null
* 159
* @param item 项 不能为null
* 160
* @return 值
* 161
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 167
* 获取hashKey对应的所有键值
* 168
*
* @param key 键
* 169
* @return 对应的多个键值
* 170
*/
public Map hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* 176
* HashSet
* 177
*
* @param key 键
* 178
* @param map 对应多个键值
* 179
* @return true 成功 false 失败
* 180
*/
public boolean hmset(String key, Map map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 192
* HashSet 并设置时间
* 193
*
* @param key 键
* 194
* @param map 对应多个键值
* 195
* @param time 时间(秒)
* 196
* @return true成功 false失败
* 197
*/
public boolean hmset(String key, Map map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 212
* 向一张hash表中放入数据,如果不存在将创建
* 213
*
* @param key 键
* 214
* @param item 项
* 215
* @param value 值
* 216
* @return true 成功 false失败
* 217
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 229
* 向一张hash表中放入数据,如果不存在将创建
* 230
*
* @param key 键
* 231
* @param item 项
* 232
* @param value 值
* 233
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* 234
* @return true 成功 false失败
* 235
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 250
* 删除hash表中的值
* 251
*
* @param key 键 不能为null
* 252
* @param item 项 可以使多个 不能为null
* 253
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 259
* 判断hash表中是否有该项的值
* 260
*
* @param key 键 不能为null
* 261
* @param item 项 不能为null
* 262
* @return true 存在 false不存在
* 263
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* 269
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* 270
*
* @param key 键
* 271
* @param item 项
* 272
* @param by 要增加几(大于0)
* 273
* @return 274
*/
public double hincr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* 280
* hash递减
* 281
*
* @param key 键
* 282
* @param item 项
* 283
* @param by 要减少记(小于0)
* 284
* @return 285
*/
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 292
* 根据key获取Set中的所有值
* 293
*
* @param key 键
* 294
* @return 295
*/
public Set sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 306
* 根据value从一个set中查询,是否存在
* 307
*
* @param key 键
* 308
* @param value 值
* 309
* @return true 存在 false不存在
* 310
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 321
* 将数据放入set缓存
* 322
*
* @param key 键
* 323
* @param values 值 可以是多个
* 324
* @return 成功个数
* 325
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 336
* 将set数据放入缓存
* 337
*
* @param key 键
* 338
* @param time 时间(秒)
* 339
* @param values 值 可以是多个
* 340
* @return 成功个数
* 341
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 355
* 获取set缓存的长度
* 356
*
* @param key 键
* 357
* @return 358
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 369
* 移除值为value的
* 370
*
* @param key 键
* 371
* @param values 值 可以是多个
* 372
* @return 移除的个数
* 373
*/
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
// ===============================list=================================
/**
* 386
* 获取list缓存的内容
* 387
*
* @param key 键
* 388
* @param start 开始
* 389
* @param end 结束 0 到 -1代表所有值
* 390
* @return 391
*/
public List lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 402
* 获取list缓存的长度
* 403
*
* @param key 键
* 404
* @return 405
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 416
* 通过索引 获取list中的值
* 417
*
* @param key 键
* 418
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* 419
* @return 420
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 431
* 将list放入缓存
* 432
*
* @param key 键
* 433
* @param value 值
* 434
* @param time 时间(秒)
* 435
* @return 436
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 467
* 将list放入缓存
* 468
*
* @param key 键
* 469
* @param value 值
* 470
* @param time 时间(秒)
* 471
* @return 472
*/
public boolean lSet(String key, List value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 484
* 将list放入缓存
* 485
*
* 486
*
* @param key 键
* 487
* @param value 值
* 488
* @param time 时间(秒)
* 489
* @return 490
*/
public boolean lSet(String key, List value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 504
* 根据索引修改list中的某条数据
* 505
*
* @param key 键
* 506
* @param index 索引
* 507
* @param value 值
* 508
* @return 509
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 521
* 移除N个值为value
* 522
*
* @param key 键
* 523
* @param count 移除多少个
* 524
* @param value 值
* 525
* @return 移除的个数
* 526
*/
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
private void setDatabase(int num) {
LettuceConnectionFactory con=(LettuceConnectionFactory) redisTemplate.getConnectionFactory();
if(con!=null && num!=con.getDatabase()) {
con.setDatabase(num);
redisTemplate.setConnectionFactory(con);
con.resetConnection();
}
}
}