java秒杀高并发---项目框架搭建 将redis集成,前缀的设置

Spring Boot环境搭建

Spring Boot 文档
https://docs.spring.io/spring-boot/docs/1.5.2.RELEASE/reference/htmlsingle/

配置模板Thymeleaf配置

#thymeleaf start
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.content-type=text/html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false
#thymeleaf end

mybatis
依赖

<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.3.2</version>
</dependency>

配置

#mybatis
#数据库中对应的表的实体类
mybatis.type-aliases-package=com/example/demo/domain
#下划线转换与实体类
mybatis.configuration.map-underscore-to-camel-case=true
mybatis.configuration.default-fetch-size=100
mybatis.configuration.default-statement-timeout=3000

druid配置

#druid
spring.datasource.url=jdbc:mysql://localhost:3306/miaosha?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
#连接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

Spring-Boot集成 redis

添加 Jedis依赖

添加 Fastjson依赖(将java对象序列化写到redis中)

序列化后是 json格式的

<dependency>
   <groupId>redis.clients</groupId>
   <artifactId>jedis</artifactId>
</dependency>

<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>fastjson</artifactId>
   <version>1.2.38</version>
</dependency>

配置

#redis
redis.host=localhost
redis.port=6379
redis.password=123456
redis.timeout=3
redis.poolMaxTotal=10
redis.poolMaxidle=10
redis.poolMaxWait=3

创建 redis的配置类使用了 @ConfigurationProperties注解 要加入下面的依赖
https://docs.spring.io/spring-boot/docs/1.5.12.RELEASE/reference/html/configuration-metadata.html#configuration-metadata-annotation-processor

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

redis配置类

package com.example.demo.redis;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;


/**
* Created by Administrator on 2018/5/3.
*/
@Component
@ConfigurationProperties(prefix="redis")
public class RedisConfig {
    private String host;
    private int port;
    private int timeout;
    private String password;
    private int poolMaxTotal;
    private int poolMaxidle;
    private int poolMaxWait;
    all get and set

写一个操作redis的逻辑类
里面有 get和set

通过redis配置类,通过redis池创建返回一个jedis,再去操作。
将对象序列化传入 redis中。

package com.example.demo.service;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import com.example.demo.redis.RedisConfig;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
@Service
public class RedisService {

    @Autowired
    RedisConfig redisConfig;

    @Autowired
    JedisPool jedisPool;

    public <T> T get(String key,Class<T> clazz){
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            String str = jedis.get(key);
            //把str转为Bean输出
            T t = stringToBean(str,clazz);
            return t;
        }finally {
            returnToPool(jedis);
        }
   }

    public <T> boolean set(String key, T value){
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            String str = beanToString(value);
            if(str==null|| str.length()<=0){
                return false;
            }
           jedis.set(key,str);
        }finally {
            returnToPool(jedis);
        }


        return false;
    }

  //通过fastjson把字符串转为bean
    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);
        }
    }
 //bean转为字符串
    private <T>String beanToString( T value){
        //判断这个value是什么类型,然后针对的进行转为字符串
        //可以为int,字符串,对象等等
        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);
        }
        //关闭连接
    private void returnToPool(Jedis jedis){
        if (jedis!=null) {
            jedis.close();
        }
    }
  @Bean
    public JedisPool JedispPoolFactory(){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
        poolConfig.setMaxIdle(redisConfig.getPoolMaxidle());
        poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait()*1000);
        JedisPool jp = new JedisPool(poolConfig,redisConfig.getHost(),redisConfig.getPort(),
                redisConfig.getTimeout()*1000,redisConfig.getPassword(),0);
        return jp;
    }

}

之前在 redis中进行了设置 set key

get获取
这里写图片描述

这么写对key的操作太有问题了。
于是对这个key加个前缀。

前缀不同加上 key就是真正的key

通用缓存 Key封装

接口<–抽象类<–实现类

什么意思呢~
先定义个接口 定义两个方法,一个获取前缀,一个获取过期时间

public interface KeyPrefix {

    //过期时间
    public int expireSeconds();
    //前缀
    public String getPrefix();
}

定义个抽象类
定义两个属性,一个是过期时间,一个是前缀
如果没有传入过期时间就是永不过期的创建这个构造函数
然后这个前缀的定义。如何定义
类名+加上前缀就是前缀了。

public abstract class BasePrefix implements KeyPrefix{

    private int expireSeconds;

    private String Prefix;

    //默认创建永不过期的
    public BasePrefix(String prefix) {
        this.expireSeconds = 0;
        Prefix = prefix;
    }


    public BasePrefix(int expireSeconds, String prefix) {
        this.expireSeconds = expireSeconds;
        Prefix = prefix;
    }


    public int expireSeconds() {
        return expireSeconds;
    }


    public String getPrefix() {
        //那么不同模块如何保证前缀不一样。可以使用类名,不同key,创建
        //不同类
        String className = getClass().getSimpleName();
        return className+":"+Prefix;
    }
}

定义一个实现类,比如是对用户的key的定义

不允许外部创建,只能静态获取一个 对象实例。
这里定义了两种 prefix 一个是id,一个是name

public class UserKey extends BasePrefix {

    private UserKey(String prefix) {
        super( prefix);
    }

    public static UserKey getById = new UserKey("id");
    public static UserKey getGetByName = new UserKey("name");
}

比如我们这里我们使用 id。那么最后的key是 UserKey:id key
这里的key就使用这个用户的id。
所以控制器如下



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

    @RequestMapping(value = "/redis/set")
    @ResponseBody
    public boolean redisSet(){
        User user = new User(1,"Recar");
        boolean ret = redisService.set(UserKey.getById,""+1,user);
        return ret;
    }

这里写图片描述

增加自增和自减的方法

//增加一个值
public <T> Long incr(KeyPrefix prefix, String key){
    Jedis jedis = null;
    try{
        jedis = jedisPool.getResource();
        //生成真正的key
        String realKey = prefix.getPrefix()+key;
        return  jedis.incr(realKey);

    }finally {
        returnToPool(jedis);
    }

}

//减少一个值
public <T> Long decr(KeyPrefix prefix, String key){
    Jedis jedis = null;
    try{
        jedis = jedisPool.getResource();
        //生成真正的key
        String realKey = prefix.getPrefix()+key;
        return  jedis.decr(realKey);

    }finally {
        returnToPool(jedis);
    }
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值