springboot 实现redis高并发抢票服务

第一步:添加依赖

<?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 https://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.5.4</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wei</groupId>
    <artifactId>qiangpiao</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>qiangpiao</name>
    <description>qiangpiao</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.4.7.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

第二步:配置文件内容

server.port=8080
spring.data.redis.host=127.0.0.1
spring.data.redis.port=6379
ticket.total=12
spring.data.redis.password=abc123456

第三步:注册jedis对象

package com.wei.qiangpiao.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisClientConfig;

import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 注册jedis对象
 */
@Configuration
public class JedisConfig {
    @Autowired
    Environment env;
//    //创建线程池
//    public static ThreadPoolExecutor pool = new ThreadPoolExecutor(
//            10, 100, 10, TimeUnit.SECONDS,
//            new LinkedBlockingDeque<Runnable>()
//    );
//
//    @Bean
//    public Jedis getJedis() {
//
//        //jedis操作redis,连接配置信息,本地连接
//        Jedis jedis = new Jedis(env.getProperty("spring.data.redis.host"), Integer.parseInt(env.getProperty("spring.data.redis.port")));
//        //登录redis密码
//        jedis.auth("abc123456");
//    }

    @Bean
    public Jedis getJedis(){
        return new Jedis(new HostAndPort(
                env.getProperty("spring.data.redis.host"),
                env.getProperty("spring.data.redis.port", Integer.class)
        ),new JedisClientConfig(){
            public int getConnectionTimeoutMillis() {// 超时毫秒数
                return 2000;
            }

            public String getPassword() {// 密码默认为空
                return env.getProperty("spring.data.redis.password");
            }
        }
        );
    }
}

第四步:购票服务Service

package com.wei.qiangpiao.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

@Service
public class TicketsService {
    @Autowired
    Jedis jedis;

    @Value("${ticket.total}")
    Long total;

    final String COUNT_KEY = "ticketsCount";//自增的已售卖票数
    final String FINAL_KEY = "scramble.finsh";//抢票活动结束

    public String scramble(){
        String finsh = jedis.get(FINAL_KEY);//获取结束状态
        if (!"true".equals(finsh)) { //如果抢购未结束
            long incr = jedis.incr(COUNT_KEY);//出一张票
            if (incr <= total) {
                return String.format("ticket%03d", incr);//还有票就出票
            }else{
                jedis.set(FINAL_KEY, "true");   //抢购状态设置为结束
            }
        }
        return "没有票了";
    }
}

第五步:控制器

package com.wei.qiangpiao.controller;

import com.wei.qiangpiao.service.TicketsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@Controller
public class TicketController {
    @Autowired
    TicketsService ticketsService;
    @GetMapping("/scramble")
    @ResponseBody
    public String grab(){
        String ticketNum = ticketsService.scramble();//抢票
        if (ticketNum == null) {
            return "所有的票都抢完了";
        }else{
            return "你抢到的票号为:"+ticketNum;
        }
    }

    @GetMapping("/index")
    public String index(){
        return "buyticket";
    }
}

第六步:简单前端页面测试

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>抢票页面</title>
</head>
<body>
<a href="/scramble" style="font-size: 18px">立即抢票</a>
</body>
</html>

第七步:打开地址:localhost:8080/index.html

当超过12张票时,显示没票

猜你喜欢

转载自blog.csdn.net/qq_35207086/article/details/128276548