代码中调用 linux 命令批量删除指定redis缓存数据

本文介绍了一种通过定时任务批量删除Redis缓存的方法,利用Linux脚本配合远程执行工具实现按日或按月清理指定前缀的key-value集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在业务中为了分类匹配key,如:
需要当月内要缓存的key:
这里写图片描述
登陆时的key:
这里写图片描述

等,需要处理分类批量删除key-value的集合。
适用定时任务定时调用linux服务器上的命令脚本,进行定时批量删除。

调用执行服务器上脚本的代码:

public class delRedisCacheCentUsers {
    private Logger logger = LoggerFactory.getLogger(delRedisCacheCentUsers.class);
    private static String addr;
    private static String username;
    private static String pwd;
    private static String shellPathByDay;
    private static String shellPathByMonth;
    /**
     * 删除
     */
    static{
        Properties prop = new Properties();
        try {
            String file = delRedisCacheCentUsers.class.getResource("/jedisPool_Tran.properties").getFile();
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            prop.load(in);
            addr = prop.getProperty("REDIS.HOST");
            username = prop.getProperty("REDIS.NAME");
            pwd = prop.getProperty("REDIS.PWD");
            shellPathByDay = prop.getProperty("shellPathByDay");
            shellPathByMonth = prop.getProperty("shellPathByMonth");

//            System.out.println("===load "+addr+" "+username+" "+pwd);

        }catch (Exception e){
            try {
                throw new Exception("== load redis prop fail!");
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
    }

    /**
     * 日定时任务,删除当日缓存
     */
    public void delCurrentDayCacheUsersByDay(){
        JedisPooler jedisPooler = null;
        Jedis jedis = null;

        try{
             jedisPooler = RedisPoolerFactory.getJedisPooler();
             jedis = jedisPooler.getJedis();
            /**
             * 删除缓存的用户对应的积分行为和次数
             */
            RemoteShellTool tool = new RemoteShellTool(addr, username,
                    pwd, "utf-8");
            String result = tool.exec(shellPathByDay);
//        System.out.println("==result: "+result);
            //删除日上线  /usr/bin/redis-cli keys "day_userCentOpers|*" | xargs -i /usr/bin/redis-cli del {}
            if (result.toLowerCase().contains("success")){
                logger.info("===[DEL USERS SUCCESS]!");
            }else{
                logger.error("===[DEL USERS FAIL]!");

            }

        }catch(Exception e){
            e.printStackTrace();

        }finally {

            if (jedis != null){
                jedisPooler.returnResource(jedis);

            }
        }
    }



    /**
     * 月定时任务,删除当月缓存 
     */
    public void delCurrentDayCacheUsersByMonth(){
        JedisPooler jedisPooler = null;
        Jedis jedis = null;
        try{
            jedisPooler = RedisPoolerFactory.getJedisPooler();
            jedis = jedisPooler.getJedis();
            /**
             * 删除缓存的用户对应的积分行为和次数
             */
            RemoteShellTool tool = new RemoteShellTool(addr, username,
                    pwd, "utf-8");
            String result = tool.exec(shellPathByMonth);
//        System.out.println("==result: "+result);
            //删除日上线  /usr/bin/redis-cli keys "day_userCentOpers|*" | xargs -i /usr/bin/redis-cli del {}
            if (result.toLowerCase().contains("success")){
                logger.info("===[DEL USERS SUCCESS BY MONTH]!");
            }else{
                logger.error("===[DEL MONTH USERS FAIL]!");

            }

        }catch(Exception e){
            e.printStackTrace();

        }finally {

            if (jedis != null){
                jedisPooler.returnResource(jedis);

            }
        }
    }
}

在redis的配置文件redis.properties中顺便定义了脚本路径:

shellPathByDay=/usr/local/sbin/delRedisCacheUsersByDay.sh
shellPathByMonth=/usr/local/sbin/delRedisCacheUsersByMonth.sh

对应脚本命令:

delRedisCacheUsersByDay.sh:
//删除以  'day_userCentOpers| '为前缀的key-value
/usr/bin/redis-cli keys "day_userCentOpers|*" | xargs -i /usr/bin/redis-cli del {}

//删除以  'month_userCentOpers| '为前缀的key-value
delRedisCacheUsersByMonth.sh:
/usr/bin/redis-cli keys "month_userCentOpers|*" | xargs -i /usr/bin/redis-cli del {}

这里是定时任务的xml文件,实现调用操作方法:

<!--定时任务1-->
    <!-- 每天12点将当天用户积分行为缓存清掉  -->
    <bean id="deleteRedisCacheDayUsersJob" class="cn.qtone.xxt.cent.quartz.delRedisCacheCentUsers" />
    <bean id="deleteRedisCacheDayUsersTask" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject" ref="deleteRedisCacheDayUsersJob" />
        <property name="targetMethod" value="delCurrentDayCacheUsersByDay" /><!-- 定时执行 doItem 方法 -->
        <property name="concurrent" value="false" />
    </bean>
    <bean id="deleteRedisCacheDayUsersTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
        <property name="jobDetail" ref="deleteRedisCacheDayUsersTask" />
        <property name="cronExpression" value="59 59 23 * * ?" /><!-- 每天凌晨23:59:59 点执行 -->
        <!--<property name="cronExpression" value="0 */1 * * * ?" />&lt;!&ndash; 每隔1min执行一次 &ndash;&gt;-->
    </bean>
    <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                 <ref bean="deleteRedisCacheDayUsersTrigger" />
                <ref bean="deleteRedisCacheMonthUsersTrigger" />
                <!--暂时不用-->
                 <!--<ref bean="centUpdateByMonthTrigger" />-->
            </list>
        </property>
    </bean>

远程调用shell脚本类:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;

/**
 * 远程调用服务器上shell脚本
 * Created with CentSystem
 */
public class RemoteShellTool {

    private Connection conn;
    private String ipAddr;
    private String charset = Charset.defaultCharset().toString();
    private String userName;
    private String password;

    public RemoteShellTool(String ipAddr, String userName, String password,
                           String charset) {
        this.ipAddr = ipAddr;
        this.userName = userName;
        this.password = password;
        if (charset != null) {
            this.charset = charset;
        }
    }

    public boolean login() throws IOException {
        conn = new Connection(ipAddr);
        conn.connect(); // 连接
        return conn.authenticateWithPassword(userName, password); // 认证
    }

    public String exec(String cmds) {
        InputStream in = null;
        String result = "";
        try {
            if (this.login()) {
                Session session = conn.openSession(); // 打开一个会话
                session.execCommand(cmds);

                in = session.getStdout();
                result = this.processStdout(in, this.charset);
                session.close();
                conn.close();
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return result;
    }

    public String processStdout(InputStream in, String charset) {

        byte[] buf = new byte[1024];
        StringBuffer sb = new StringBuffer();
        try {
            while (in.read(buf) != -1) {
                sb.append(new String(buf, charset));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        RemoteShellTool tool = new RemoteShellTool("192.168.120.XXX", "ubuntu",
                "xxxxx", "utf-8");
        String result = tool.exec("/usr/local/sbin/xxx.sh");
        System.out.print("===result:"+result);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值