欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java秒杀系统方案优化

程序员文章站 2022-06-20 08:58:26
...

Java秒杀系统方案优化

搭建项目

使用spring boot搭建项目建立相关的包名、类名。

mybatis的相关配置

1.加入mybatis相关的依赖
2.在application.properties配置文件中写配置mybatis相关的代码

spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/miaosha?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=123456789

3.测试数据库是否连接,相应的dao层代码

@Mapper
public interface UserDao {
    
    @Select("select * from user where id=#{id}")
    List <User> getById(@Param("id")int id);
}

controller层相应的代码如下

    @RequestMapping("/redis/get")
    @ResponseBody
    public Result<User> redisGet(){
        User user = redisService.get(UserKey.getById, ""+1, User.class);
        return Result.success(user);
    }

Redis相关的配置和安装

  1. 阿里云服务器安装redis
  2. 安装redis镜像: Docker pull redis
  3. 启动redis镜像:docker run -p 6379:6379--name redis -d redis:latest  --requirepass “123456” 	
     进入redis镜像:docker exec -it redis redis-cli -a 123456 	
      添加数据:set name xiaomianyang 	
      读取数据:get name
    
  4. 使用可视化工具(RedisDesktopManager) 建立远程连接
  5. 使用idea远程使用redis
  6. Maven配置
       <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
  1. 和搭建Mybatis一样相关的配置信息也是存放在properties上的,相关代码如下:
redis.host=182.92.170.161
redis.port=6379
redis.timeout=3
redis.password=123456
redis.poolMaxTotal=10
redis.poolMaxIdle=10
redis.poolMaxWait=3

  1. 编写bean来获取配置信息,代码如下:
@Component
@ConfigurationProperties(prefix = "redis")
public class RedisConfig {
    private String host;
    private int port;
    private int timeout;
    private String password;
    private int poolMaxTotal;

[email protected](把properties中redis开头的信息注入到相关的属性中)

  1. 接下来编写项目中redis的Service类,把redis的一些常用的get,set,exists,detete,incr,decr封装,
@Service
public class RedisService {

    @Autowired
    JedisPool jedisPool;


    public <T> T get(KeyPrefix prefix, String key,Class<T>clazz){

        Jedis jedis=null;
        try {
           jedis= jedisPool.getResource();
            String realKey = prefix.getPrefix() + key;
            String str = jedis.get(realKey);
            T t=stringToBean(str,clazz);
            return t;
        }finally {
            returnToPool(jedis);
        }
    }


    private <T> T stringToBean(String str,Class<T>clazz) {
            if (str ==null||str.length()<=0||clazz==null){
                return null;
            }
            if (clazz ==int.class||clazz == Integer.class){
                return (T)Integer.valueOf(str);
            }else if (clazz ==String.class){
                return (T)str;
            }else if (clazz ==long.class||clazz== Long.class){
                return (T)Long.valueOf(str);
            }else{
                return JSON.toJavaObject(JSON.parseObject(str),clazz);
            }
        }


    public <T> boolean set(KeyPrefix prefix,String key,T value){

        Jedis jedis=null;
        try {
         jedis= jedisPool.getResource();
         String str =beanToString(value);
         if (str == null|| str.length() <=0){
             return false;
         }
         String realKey = prefix.getPrefix() + key;
            int seconds = prefix.expireSeconds();
            if (seconds <= 0) {
                jedis.set(realKey, str);
            }else  {
                jedis.setex(realKey, seconds, str);
            }
            return true;
        }finally {
            returnToPool(jedis);
        }
    }

    private <T> String beanToString(T value) {
        if (value == null){
            return null;
        }
       Class<?>clazz= value.getClass();
        if (clazz ==int.class||clazz== Integer.class){
            return ""+value;
        }else if (clazz ==String.class){
            return (String)value;
        }else if (clazz ==long.class||clazz== Long.class){
            return ""+value;
    }else{
            return JSON.toJSONString(value);
        }


    }

    public Boolean exists(KeyPrefix prefix, String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realPrefix = prefix.getPrefix() + key;
            return jedis.exists(realPrefix);
        }finally {
            returnToPool(jedis);
        }
    }

    public Long incr(KeyPrefix prefix, String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realPrefix = prefix.getPrefix() + key;
            return jedis.incr(realPrefix);
        }finally {
            returnToPool(jedis);
        }
    }

    public Long decr(KeyPrefix prefix, String key){
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            String realPrefix = prefix.getPrefix() + key;
            return jedis.decr(realPrefix);
        }finally {
            returnToPool(jedis);
        }
    }

    private void returnToPool(Jedis jedis){
        if (jedis !=null){
            jedis.close();
        }
    }


}