Java分布式锁(6种实现方法)

Java分布式锁(6种实现方法)目录Java分布式锁一、基于ReentrantLock锁解决超卖问题(单体)1.1、重要代码1.2、测试代码二、基于数据库的分布式锁(分布式)2.1、重要代码2.2、重要sql语句2.3、测试三、基于redis分布式锁3.1、重要代码3.2、yml配置四、基于分布式锁解决定时任务重复问题4.1、封装redis分布式锁4.2、重要代码4.3、解决任务重复五、zookeeper分布式锁代码实现5.1…

大家好,又见面了,我是你们的朋友全栈君。

Java分布式锁


方式 优点 缺点
数据库 实现简单、易于理解 对数据库压力大
Redis 易于理解 自己实现、不支持阻塞
Zookeeper 支持阻塞 需理解Zookeeper、程序复杂
Curator(推荐) 提供锁的方法 依赖Zookeeper、强一致
Redisson(推荐) 提供锁的方法,可阻塞

一、基于ReentrantLock锁解决超卖问题(单体)

1.1、重要代码

package com.example.distributedemo.service;

import com.example.distributedemo.dao.OrderItemMapper;
import com.example.distributedemo.dao.OrderInfoMapper;
import com.example.distributedemo.dao.ProductMapper;
import com.example.distributedemo.model.orderInfo;
import com.example.distributedemo.model.OrderItem;
import com.example.distributedemo.model.Product;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Service
@Slf4j
public class OrderService { 
   

    @Resource
    private OrderInfoMapper orderMapper;
    @Resource
    private OrderItemMapper orderItemMapper;
    @Resource
    private ProductMapper productMapper;
    
    //购买商品id
    private Integer  purchaseProductId = 1;
    //购买商品数量
    private int purchaseProductNum = 1;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;
    @Autowired
    private TransactionDefinition transactionDefinition;

    private Lock lock = new ReentrantLock();


    public Integer createOrder() throws Exception{ 
   
        Product product = null;

        lock.lock();

        try { 
   
            // 根据事务定义TransactionDefinition,获取事务
            TransactionStatus transaction1 = platformTransactionManager.getTransaction(transactionDefinition);
            product = productMapper.selectByPrimaryKey(purchaseProductId);
            if (product==null){ 
   
                // 回滚事务
                platformTransactionManager.rollback(transaction1);
                throw new Exception("购买商品:"+purchaseProductId+"不存在");
            }

            // 商品当前库存
            Integer currentCount = product.getCount();
            System.out.println(Thread.currentThread().getName()+"库存数:"+currentCount);
            // 校验库存
            if (purchaseProductNum > currentCount){ 
   
                // 回滚事务
                platformTransactionManager.rollback(transaction1);
                throw new Exception("商品"+purchaseProductId+"仅剩"+currentCount+"件,无法购买");
            }

            Product product1 = new Product();
            product1.setId(purchaseProductId);
            product1.setCount(0);

            productMapper.updateByPrimaryKeySelective(product1);
            // 提交事务
            platformTransactionManager.commit(transaction1);

        }finally { 
   
            lock.unlock();
        }

        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition);
        orderInfo order = new orderInfo();
        order.setId(1);
        order.setOrderName(product.getName());
        order.setAmount(product.getPrice().multiply(new BigDecimal(purchaseProductNum)));
        order.setOrderStatus(1);//待处理
        orderMapper.insertSelective(order);

        OrderItem orderItem = new OrderItem();
        orderItem.setId(1);
        orderItem.setOrderId(order.getId());
        orderItem.setProductId(product.getId());

        orderItemMapper.insertSelective(orderItem);
        platformTransactionManager.commit(transaction);

        return order.getId();
    }

}

1.2、测试代码

package com.example;

import com.example.distributedemo.DistributeDemoApplication;
import com.example.distributedemo.service.OrderService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = DistributeDemoApplication.class)
public class DistributeDemoApplicationTests { 
   

    @Autowired
    private OrderService orderService;

    @Test
    public void concurrentOrder() throws InterruptedException { 
   
        CountDownLatch cdl = new CountDownLatch(5);
        CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
        ExecutorService es = Executors.newFixedThreadPool(5);

        for (int i =0;i<5;i++){ 
   
            es.execute(()->{ 
   
                try { 
   
                    cyclicBarrier.await();
                    Integer orderId = orderService.createOrder();
                    System.out.println("订单id:"+orderId);
                } catch (Exception e) { 
   
                    e.printStackTrace();
                }finally { 
   
                    cdl.countDown();
                }
            });
        }
        cdl.await();
        es.shutdown();
    }

}

二、 基于数据库的分布式锁(分布式)

2.1、重要代码

package com.example.distributedemo.controller;

import com.example.distributedemo.dao.DistributeLockMapper;
import com.example.distributedemo.model.DistributeLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 14:56
 * @description  基于数据库的分布式锁
 */
@Slf4j
@RestController
public class DemoController { 
   

    @Resource
    private DistributeLockMapper distributeLockMapper;

    @RequestMapping("/singleLock")
    @Transactional(rollbackFor = Exception.class)
    public String singleLock() throws Exception { 
   
        log.info("已经进入方法!");
        DistributeLock distributeLock = distributeLockMapper.selectDistributeLock("demo");
        if (distributeLock == null){ 
   
            throw new Exception("分布式锁找不到");
        }
        log.info("已经进入了锁!");
        Thread.sleep(30000);
        return "我已经执行完成!";
    }

}

2.2、重要sql语句

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.distributedemo.dao.DistributeLockMapper">
  <resultMap id="BaseResultMap" type="com.example.distributedemo.model.DistributeLock">
    <!--
      WARNING - @mbg.generated
    -->
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="business_code" jdbcType="VARCHAR" property="businessCode" />
    <result column="business_name" jdbcType="VARCHAR" property="businessName" />
  </resultMap>

  <select id="selectDistributeLock" resultType="com.example.distributedemo.model.DistributeLock">
    select *from distribute_lock
    where business_code = #{businessCode}
    for update
  </select>
</mapper>

2.3、测试

http://localhost:8081/singleLock
http://localhost:8082/singleLock

三、基于redis分布式锁

3.1、重要代码

package com.example.distributedemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.awt.print.Book;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 17:05
 * @description 基于redis分布式锁
 */

@RestController
@Slf4j
public class RedisLockController { 
   

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/redisLock")
    public String redisLock() throws InterruptedException { 
   
        log.info("我进入了方法");

        String key = "redisKey";
        String value = UUID.randomUUID().toString();

        RedisCallback<Boolean> redisCallback = redisConnection -> { 
   
            // 设置NX
            RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent();
            // 设置过期时间
            Expiration expiration = Expiration.seconds(30);

            // 序列化key和value
            byte[] redisKey = redisTemplate.getKeySerializer().serialize(key);
            byte[] redisValue = redisTemplate.getValueSerializer().serialize(value);

            // 执行set nx 操作
            Boolean result = redisConnection.set(redisKey, redisValue, expiration, setOption);
            return result;
        };

        // 获取分布式锁
        Boolean lock = (Boolean) redisTemplate.execute(redisCallback);
        if (lock) { 
   
            log.info("我进入了锁!");
            Thread.sleep(15000);
        }

        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                " return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                " return 0\n" +
                "end";
        RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class);
        List<String> keys = Arrays.asList(key);

        Boolean result = (Boolean) redisTemplate.execute(redisScript, keys, value);
        log.info("释放锁的结果:" + result);


        log.info("方法执行完成");
        return "方法执行完成";
    }
}

3.2、yml配置

spring.datasource.username=root
spring.datasource.password=1999114zzm
spring.datasource.url=jdbc:mysql://localhost:3306/fen_bu_shi_suo?serverTimezone=Asia/Shanghai&useSSL=false


mybatis.mapper-locations=/mapper/*.xml
logging.pattern.dateformat=HH:mm:ss

spring.redis.host=你ip
spring.redis.port=6379

四、基于分布式锁解决定时任务重复问题

4.1、封装redis分布式锁

package com.example.distributedemo.lock;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 17:46
 * @description 描述
 */
@Slf4j
public class RedisLockUtils implements AutoCloseable{ 
   

    private RedisTemplate redisTemplate;
    private String key;
    private String value;
    // 单位:秒
    private int expireTime;

    public RedisLockUtils(RedisTemplate redisTemplate, String key, int expireTime) { 
   
        this.redisTemplate = redisTemplate;
        this.key = key;
        this.value = UUID.randomUUID().toString();
        this.expireTime = expireTime;
    }

    /**
     * 获取分布式锁
     * @return
     */
    public boolean getLock() { 
   
        RedisCallback<Boolean> redisCallback = redisConnection -> { 
   
            // 设置NX
            RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent();
            // 设置过期时间
            Expiration expiration = Expiration.seconds(expireTime);

            // 序列化key和value
            byte[] redisKey = redisTemplate.getKeySerializer().serialize(key);
            byte[] redisValue = redisTemplate.getValueSerializer().serialize(value);

            // 执行set nx 操作
            Boolean result = redisConnection.set(redisKey, redisValue, expiration, setOption);
            return result;
        };

        // 获取分布式锁
        Boolean lock = (Boolean) redisTemplate.execute(redisCallback);

        return lock;
    }

    /**
     * 释放锁
     * @return
     */
    public boolean unLock() { 
   
        String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                " return redis.call(\"del\",KEYS[1])\n" +
                "else\n" +
                " return 0\n" +
                "end";
        RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class);
        List<String> keys = Arrays.asList(key);

        Boolean result = (Boolean) redisTemplate.execute(redisScript, keys, value);
        log.info("释放锁的结果:" + result);
        return result;
    }

    @Override
    public void close() throws Exception { 
   
        // 释放锁
        unLock();
    }
}

4.2、重要代码

package com.example.distributedemo.controller;

import com.example.distributedemo.lock.RedisLockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 17:05
 * @description 描述
 */

@RestController
@Slf4j
public class RedisLockController { 
   

    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("/redisLock")
    public String redisLock() throws InterruptedException { 
   
        log.info("我进入了方法");

        // 获取锁
        try(RedisLockUtils redisLock = new RedisLockUtils(redisTemplate, "redisKey", 30)) { 
   

            boolean lock = redisLock.getLock();

            if (lock) { 
   
                log.info("我进入了锁!");
                Thread.sleep(15000);
            }

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

        log.info("方法执行完成");
        return "方法执行完成";
    }
}

4.3、解决任务重复

  • 启动类
package com.example.distributedemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
@EnableScheduling // 开启定时任务
public class DistributeDemoApplication { 
   

    public static void main(String[] args) { 
   
        SpringApplication.run(DistributeDemoApplication.class, args);
    }

}
  • 定时任务
package com.example.distributedemo.service;

import com.example.distributedemo.lock.RedisLockUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 18:17
 * @description 描述
 */
@Service
@Slf4j
public class SchedulerService { 
   

    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron = "0/5 * * * * ?")
    public void sendSms() { 
   
        try(RedisLockUtils redisLock = new RedisLockUtils(redisTemplate, "autoSms", 30)) { 
   
            boolean lock = redisLock.getLock();

            if (lock) { 
   
                log.info("向138xxxxx用户发短信!");
            }
        }catch (Exception e) { 
   
            e.printStackTrace();
        }
    }
}

五、zookeeper分布式锁代码实现

5.1、重要代码

package com.example.distributedemo.lock;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 18:52
 * @description 描述
 */
@Slf4j
public class ZkLock implements AutoCloseable, Watcher { 
   

    private ZooKeeper zooKeeper;
    private String znode;

    public ZkLock() throws IOException { 
   
        this.zooKeeper = new ZooKeeper("49.232.26.207:2181", 60000, this);
    }

    public boolean getLock(String businessCode) { 
   

        try { 
   
            // 创建业务根节点
            Stat stat = zooKeeper.exists("/" + businessCode, false);
            if (stat==null){ 
   
                zooKeeper.create("/" + businessCode,
                        businessCode.getBytes(),
                        ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.PERSISTENT);
            }

            // 创建瞬时有序节点 /order/order_序号
            znode = zooKeeper.create("/" + businessCode + "/" + businessCode + "_",
                    businessCode.getBytes(),
                    ZooDefs.Ids.OPEN_ACL_UNSAFE,
                    CreateMode.EPHEMERAL_SEQUENTIAL);

            // 获取业务节点下所有的子节点
            List<String> childrenNodes = zooKeeper.getChildren("/" + businessCode, false);
            // 子节点排序
            Collections.sort(childrenNodes);
            // 获取序列号最小的(第一个)子节点
            String firstNode = childrenNodes.get(0);
            // 如果创建的节点时第一个子节点,则获得锁
            if (znode.endsWith(firstNode)) { 
   
                return true;
            }

            // 不是第一个子节点,则监听前一个节点
            String lastNode = firstNode;
            for (String node: childrenNodes){ 
   
                if (znode.endsWith(node)) { 
   
                    zooKeeper.exists("/" + businessCode + "/" + lastNode, true);
                    break;
                } else { 
   
                    lastNode = node;
                }
            }

            synchronized (this) { 
   
                wait();
            }

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

        return false;
    }

    @Override
    public void process(WatchedEvent watchedEvent) { 
   
        if (watchedEvent.getType() == Event.EventType.NodeDeleted) { 
   
            synchronized (this) { 
   
                notify();
            }
        }
    }

    @Override
    public void close() throws Exception { 
   
        zooKeeper.delete(znode, -1);
        zooKeeper.close();
        log.info("锁被释放");
    }
}

5.2、测试代码

package com.example.distributedemo.controller;

import com.example.distributedemo.lock.ZkLock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 19:45
 * @description 描述
 */

@RestController
@Slf4j
public class ZookeeperController { 
   

    @RequestMapping("/zkLock")
    public String zookeeperLock() { 
   
        log.info("我进入了方法");
        try(ZkLock zkLock = new ZkLock()) { 
   
            boolean order = zkLock.getLock("order");
            if (order) { 
   
                log.info("获得了锁!");
                Thread.sleep(10000);
            }
        }catch (Exception e){ 
   
            e.printStackTrace();
        }

        log.info("方法执行完成!");

        return "方法执行完成!";
    }
}

六、基于curator分布式锁(推荐)

6.1、Application启动类

package com.example.distributedemo;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableScheduling;
import tk.mybatis.spring.annotation.MapperScan;

@SpringBootApplication
public class DistributeDemoApplication { 
   

    public static void main(String[] args) { 
   
        SpringApplication.run(DistributeDemoApplication.class, args);
    }

    @Bean(initMethod = "start", destroyMethod = "close")
    public CuratorFramework getCuratorFramework() { 
   
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(30000, 3);
        CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient("49.232.26.207:2181", retryPolicy);
        return curatorFramework;
    }

}

6.2、测试代码

package com.example.distributedemo.controller;

import com.example.distributedemo.lock.ZkLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 19:45
 * @description 描述
 */

@RestController
@Slf4j
public class ZookeeperController { 
   

    @Autowired
    private CuratorFramework curatorFramework;

    @RequestMapping("/curatorLock")
    public String curatorLock() throws Exception { 
   
        log.info("我进入了方法");

        InterProcessMutex lock = new InterProcessMutex(curatorFramework, "/order");
        try { 
   
            if (lock.acquire(30, TimeUnit.SECONDS)) { 
   
                log.info("我获得了锁!");
                Thread.sleep(10000);
            }
        } catch (Exception e) { 
   
            e.printStackTrace();
        } finally { 
   
            log.info("释放了锁");
            lock.release();
        }

        log.info("方法执行完成!");

        return "方法执行完成!";
    }
}

七、基于redisson分布式锁(推荐)

7.1、测试代码

package com.example.distributedemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.concurrent.TimeUnit;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 16:53
 * @description 描述
 */

@RestController
@Slf4j
public class RedissonLockController { 
   

    @RequestMapping("/redissonLock")
    public String redissonLock() throws InterruptedException { 
   

        Config config = new Config();
        config.useSingleServer().setAddress("redis://49.232.26.207:6379");
        RedissonClient redissonClient = Redisson.create(config);

        RLock rLock = redissonClient.getLock("order");
        log.info("我进入了方法");

        rLock.lock(30, TimeUnit.SECONDS);
        log.info("获得了锁");
        Thread.sleep(15000);
        log.info("释放了锁");
        rLock.unlock();
        log.info("方法执行完成");

        return "方法执行完成";
    }
}

八、springboot引入redisson(推荐)

8.1、配置文件

spring.datasource.username=root
spring.datasource.password=1999114zzm
spring.datasource.url=jdbc:mysql://localhost:3306/fen_bu_shi_suo?serverTimezone=Asia/Shanghai&useSSL=false


mybatis.mapper-locations=/mapper/*.xml
logging.pattern.dateformat=HH:mm:ss

spring.redis.host=49.232.26.207
spring.redis.port=6379

8.2、测试文件

package com.example.distributedemo.controller;

import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @author zhuzhaoman
 * @date 2020/5/2 0002 16:53
 * @description 描述
 */

@RestController
@Slf4j
public class RedissonLockController { 
   

    @Autowired
    private RedissonClient redissonClient;

    @RequestMapping("/redissonLock")
    public String redissonLock() throws InterruptedException { 
   

        RLock rLock = redissonClient.getLock("order");
        log.info("我进入了方法");

        rLock.lock(30, TimeUnit.SECONDS);
        log.info("获得了锁");
        Thread.sleep(15000);
        log.info("释放了锁");
        rLock.unlock();
        log.info("方法执行完成");

        return "方法执行完成";
    }
}

九、完整的pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.7.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>distribute-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>distribute-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson</artifactId>
            <version>3.11.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.6.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>4.2.0</version>
        </dependency>
        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.11.2</version>
        </dependency>

        <!-- mybatis -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.3</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper</artifactId>
            <version>4.1.5</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.11</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.7</version>
                <dependencies>
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>8.0.17</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>

</project>

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/144795.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)


相关推荐

  • web页面请求的整个过程_HTTP的请求方法

    web页面请求的整个过程_HTTP的请求方法HTTP请求的完全过程1.1浏览器根据域名解析IP地址浏览器根据访问的域名找到其IP地址。DNS查找过程如下:浏览器缓存:首先搜索浏览器自身的DNS缓存(缓存的时间比较短,大概只有1分钟,且只能容纳1000条缓存),看自身的缓存中是否是有域名对应的条目,而且没有过期,如果有且没有过期则解析到此结束。 系统缓存:如果浏览器自身的缓存里面没有找到对应的条目,那么浏览器会…

  • SSL/TLS深度解析–OpenSSL 升级到最新版本

    SSL/TLS深度解析–OpenSSL 升级到最新版本

  • myeclipse10 64 安装svn插件的方式

    myeclipse10 64 安装svn插件的方式方法一:在线安装1.打开HELP->MyEclipseConfigurationCenter。切换到SoftWare标签页。2.点击AddSite打开对话框,在对话框Name输入Svn,URL中输入:http://subclipse.tigris.org/update_1.6.x3.在左边栏中找到PersonalSite中找到SVN展开。将CoreSVNK

  • translate和paraphrase的区别_conversation dialogue

    translate和paraphrase的区别_conversation dialogueTranslateMessage(&msg);TranslateMessage是用来把快捷键消息转换为字符消息,并将转换后的新消息投递到调用线程的消息队列中。由于Windows对所有键盘编码都是采用虚拟键的定义,这样当按键按下时,并不得字符消息,需要键盘映射转换为字符的消息。字符消息被投递到调用线程的消息队列中,当下一次调用GetMessage函数时被取出。…

  • AJAX中UpdatePanel以及Triggers的使用

    AJAX中UpdatePanel以及Triggers的使用1.页面定义:                           –控件和其它DIV等                                                                            2.必须定义ToolkitScriptManager(1).用到WebServi

  • 从高考落榜生到网络专家

    从高考落榜生到网络专家成功的背后,有着许多不为人知的故事,而正是这些夹杂着泪水和汗水的过去,才成就了一个个走 向成功的普通人——凌晨两点半,早已习惯了一个人坐在电脑前的我,望着屏幕,任思绪在暗夜的包容 下静静流淌,时光仿佛又定格在三年多前的那一刻:“283分”。那是被中国万千学子称为“黑色七 月”中的一天,下班回家的母亲从家门打开后说出的一个数字,虽然早知道自己不会考上大学,但如此 的成绩也多少出乎自己

    2022年10月22日

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号