The realization effect is shown as follows:



Pay attention to: This article is based on Redis integration using SpringBoot, integration steps and Redis basic operation default readers have mastered.

1. RedisTemplate obtains redis information

  • Redis cache:
// Method 1: get all information from Redis cache
Properties info = redisTemplate.getRequiredConnectionFactory().getConnection().info();

// Method 2: Obtain Redis cache specified information according to Connection:
Properties info = redisTemplate.getRequiredConnectionFactory().getConnection().info("xxx");
Copy the code

  • Mode 2 Optional parameters are as follows:

    • Server: General information about the Redis server

    • Clients: Part of the client connection

    • Memory: Information about memory consumption

    • Persistence: RDB and AOF related information

    • Stats: General statistics

    • Replication: Master/copy replicates information

    • CPU: CPU consumption statistics

    • Commandstats: Redis command statistics

    • Cluster: Redis cluster section

    • Keyspace: database-related statistics

    • It can also take the following values:

      • all: Returns all parts
      • default
  • The return value is as follows:

redis> INFO
# Server
# Redis server versionRedis_version: 999.999.999 redis_git_sha1:3 c968ff0 redis_git_dirty: 0 redis_build_id: 51089 de051945df4 redis_mode:standalone# Host operating system of Redis serverOS: Linux 4.8.0-1 - amd64 x86_64# Architecture (32 or 64 bits)
arch_bits:64
# the event handling mechanism used by Redis
multiplexing_api:epoll
atomicvar_api:atomic-builtin
# GCC version used to compile RedisGcc_version: 6.3.0PID of server process
process_id:9941
# Random identifier for Redis server (for Sentinel and clustering)
run_id:b770a8af038963f3d1b55358c2e376d0b5e00182
TCP/IP listening port
tcp_port:6379
# Number of seconds elapsed since the Redis server was started
uptime_in_seconds:1028993
# Number of days that have passed since the Redis server started
uptime_in_days:11
hz:10
# Clock increment in minutes for LRU management
lru_clock:10750613
executable:/usr/local/bin/redis-server
config_file:

# Clients
# number of connected clients (not including clients connected via slave server)
connected_clients:4
The longest output list of currently connected clients
client_longest_output_list:0
# Maximum input cache among currently connected clients
client_biggest_input_buf:0
# number of clients waiting for blocking commands (BLPOP, BRPOP, BRPOPLPUSH
blocked_clients:0

# Memory
# The amount of memory allocated by the Redis allocator, in bytes
used_memory:154272800
# Return the amount of memory allocated by Redis in a human-readable formatUsed_memory_human: 147.13 MFrom an operating system perspective, return the total amount of memory Redis has allocated. This value is consistent with the output of the top and ps commands.
used_memory_rss:160612352
# return in human-readable formatUsed_memory_rss_human: 153.17 M# Redis peak memory consumption in bytes
used_memory_peak:154319968
Return Redis peak memory consumption in human-readable formatUsed_memory_peak_human: 147.17 M# The percentage of peak memory used, i.e. (used_memory/ used_memory_peak) *100%Used_memory_peak_perc: 99.97%# Redis The memory overhead required to maintain the internal mechanisms of the dataset, including all client output buffers, query buffers, AOF rewrite buffers, and master/slave replication backlogs
used_memory_overhead:44082040
# Redis memory consumed when the server is started
used_memory_startup:510704
Used_memory -used_memory_overhead
used_memory_dataset:110190760
(used_memory_dataset/(used_memory-used_memory_startup))Used_memory_dataset_perc: 71.66% allocator_allocated: 154256264 allocator_active: 154550272 allocator_resident: 159731712Total system memory
total_system_memory:1044770816
Display the entire system memory in a more intuitive formatTotal_system_memory_human: 996.37 M# memory occupied by Lua script storage
used_memory_lua:37888
Display the memory footprint of Lua script storage in a more intuitive formatUsed_memory_lua_human: 37.00 KThe maximum memory configuration for the Redis instance
maxmemory:0
Display the maximum memory configuration for Redis instances in a more intuitive format
maxmemory_human:0B
# Elimination strategy when maxMemory is reachedMaxmemory_policy: noeviction allocator_frag_ratio: 1.00 allocator_frag_bytes: 294008 allocator_rss_ratio: 1.03 Allocator_rss_bytes: 5181440 rss_overhead_ratio: 1.01 rss_overhead_bytes: 880640Fragmentation rate, used_memory_rss/ used_memoryMem_fragmentation_ratio: 1.04 mem_fragmentation_bytes: 6422528The memory allocator used by Redis, specified at compile time. It can be liBC, Jemalloc, or TCMALloc.Lazyfree_pending_objects mem_allocator: jemalloc - 4.0.3 active_defrag_running: 0:0# Persistence, RDB Persistence and AOF Persistence
A flag that indicates whether the server is loading persistence files
loading:0
# How many seconds have passed since the last successful persistence file was created
rdb_changes_since_last_save:3813014
A flag that indicates whether the server is creating an RDB file
rdb_bgsave_in_progress:0
The UNIX timestamp of the RDB file was last successfully created
rdb_last_save_time:1570002708
A flag that records whether the last RDB file was created successfully or failed
rdb_last_bgsave_status:ok
The last RDB file was created in seconds
rdb_last_bgsave_time_sec:-1
# If the server is creating an RDB file, this field records the number of seconds that the current creation operation has taken
rdb_current_bgsave_time_sec:-1
rdb_last_cow_size:0
A flag that records whether AOF is open or not
aof_enabled:0
A flag that indicates whether the server is creating AOF files
aof_rewrite_in_progress:0
A flag that indicates whether the scheduled AOF rewrite operation should be performed after the RDB file is created
aof_rewrite_scheduled:0
# How long it took to create AOF file last time
aof_last_rewrite_time_sec:-1
If the server is creating AOF files, this field records the number of seconds that the current creation operation has taken
aof_current_rewrite_time_sec:-1
A flag that records whether the last AOF file was created successfully or failed
aof_last_bgrewrite_status:ok
aof_last_write_status:ok
aof_last_cow_size:0

# Stats, general statistics
Number of connection requests accepted by the server
total_connections_received:96
# Number of commands executed by the server
total_commands_processed:8700000
The number of commands executed by the server per secondinstantaneous_ops_per_sec:11 total_net_input_bytes:710523330 total_net_output_bytes:109073206 Instantaneous_input_kbps :1.04 instantaneous_output_KBps :0.32 rejected_connections:0 synC_full :0 sync_PARTIal_OK :0 sync_partial_err:0# Number of database keys that were automatically deleted because they expiredExpired_keys: 13569 expired_stale_perc: 0.00 expired_time_cap_reached_count: 0# Number of keys evict (evICT) due to maximum memory capacity limit
evicted_keys:0
The number of successful key searches in the database
keyspace_hits:1911035
The number of failed database keys
keyspace_misses:749427
# Number of channels currently subscribed
pubsub_channels:0
# Number of current subscribed modes
pubsub_patterns:0
# number of milliseconds spent in the last fork() operation
latest_fork_usec:0
migrate_cached_sockets:0
slave_expires_tracked_keys:0
active_defrag_hits:0
active_defrag_misses:0
active_defrag_key_hits:0
active_defrag_key_misses:0

# Replication, master/slave Replication information
# server role
role:master
# Number of connected slave serversconnected_slaves:0 master_replid:33f9e49948d61df7fa02e315ecff02bbc3b2c9aa master_replid2:0000000000000000000000000000000000000000 master_repl_offset:0 second_repl_offset:-1 repl_backlog_active:0  repl_backlog_size:1048576 repl_backlog_first_byte_offset:0 repl_backlog_histlen:0# CPUUsed_cpu_user used_cpu_sys: 925.48:3467.41 used_cpu_sys_children: used_cpu_user_children 0.00:0.00# Cluster
cluster_enabled:0

# Keyspace
db0:keys=876234,expires=3,avg_ttl=204565882
Copy the code

2. CacheController interface code

/** * Redis cache monitor Controller interface **@author csp
 */
@RestController
@RequestMapping("/monitor/cache")
public class CacheController
{
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @PreAuthorize("@ss.hasPermi('monitor:cache:list')")// Custom permission annotations
    @GetMapping()
    public AjaxResult getInfo(a) throws Exception
    {
        // Get the full redis cache information
        //Properties info = redisTemplate.getRequiredConnectionFactory().getConnection().info();
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());

        // Get redis cache command statistics
        //Properties commandStats = redisTemplate.getRequiredConnectionFactory().getConnection().info("commandstats");
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));

        // Get the total number of available keys in redis cache
        //Long dbSize = redisTemplate.getRequiredConnectionFactory().getConnection().dbSize();
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=".",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);

        returnAjaxResult.success(result); }}Copy the code

The @preauthorize (“@ss. HasPermi (‘monitor:cache:list’)”) annotation is based on Spring Security. AjaxResult returns a custom authorization object