项目第十一天

1.搭建后台环境

common模块

1.pom

 <dependencies>
        <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>

        <dependency>
            <groupId>com.sx</groupId>
            <artifactId>hrm-basic-utils</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <!--不能全部引入mybatis-plus,这是要做数据库操作,这里是不需要的,只需引入核心包解决错误而已-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus</artifactId>
            <version>2.2.0</version>
        </dependency>

    </dependencies>

Service模块

1.pom

    <dependencies>

        <!--所有provider公共依賴-->
        <dependency>
            <groupId>com.sx</groupId>
            <artifactId>hrm-user-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </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>
        <!-- Eureka 客户端依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

        <!--配置中心支持-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>


        <!--mybatis-plus支持-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

        <!--数据库支持-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>

        <dependency>
            <groupId>com.sx</groupId>
            <artifactId>hrm-common-client</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

    </dependencies>

2.生成表的代码

3.创建一个Service

接口

public interface IVerifycodeService {
    /**
     * 获取验证码
     * @param imageCodekey
     * @return
     */
    String getImageCode(String imageCodekey);

    /**
     * 发送短信验证码
     * @param params
     * @return
     */
    AjaxResult sendSmsCode(Map<String,String> params);
}

实现类

@Service
public class VerifycodeServiceImpl implements IVerifycodeService {
    @Autowired
    private SsoMapper ssoMapper;
    @Autowired
    private RedisClient redisClient;
    @Override
    public String getImageCode(String imageCodekey) {
        try {
            //1生成随机验证码
            String imageCode= VerifyCodeUtils.generateVerifyCode(6).toLowerCase();
            //2 以imageCodekey作为key存放验证到redis
            redisClient.addForTime(imageCodekey,imageCode,60*5);
            //3 生成图片验证码图片 util
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            VerifyCodeUtils.outputImage(100,40,data,imageCode);
            //3 图片通过base64加密返回
            BASE64Encoder encoder = new BASE64Encoder();
            return encoder.encode(data.toByteArray());

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

    @Override
    public AjaxResult sendSmsCode(Map<String, String> params) {
        //一 接收参数
        //手机号
        String mobile=params.get("mobile");
        //图片验证码
        String imageCode=params.get("imageCode");
        //图片验证码得key
        String imageCodeKey=params.get("imageCodeKey");
        // 二 做检验
        //2.1 图片验证 通过key从redis获取存放验证码
        String imgCodeforRedis=redisClient.get(imageCodeKey);
        if (imgCodeforRedis==null||!imageCode.equals(imgCodeforRedis)){
            return AjaxResult.me().setSuccess(false).setMessage("图片验证码不正确");
        }
        //2.2手机号的验证--判null,是否已经注册了
        if (mobile==null){
            return AjaxResult.me().setSuccess(false).setMessage("请输入正确的手机号码");
        }
        List<Sso> ssos = ssoMapper.selectList(new EntityWrapper<Sso>().eq("phone", mobile));
        if (ssos!=null && ssos.size()>0){
            return AjaxResult.me().setSuccess(false).setMessage("你的手机号已经注册了,可以直接使用");
        }
        //三 发送短信验证码
        return sendSmsCode(mobile);
    }
    //@TODO
    private AjaxResult sendSmsCode(String mobile) {
        return AjaxResult.me();
    }
}

4.创建一个controller

/**
 * 验证码的类型
 * 图像验证码
 * 短信验证码
 */
@RestController
@RequestMapping("/verifycode")
public class VerifycodeController {
    @Autowired
    private IVerifycodeService verifycodeService;

    /**
     *
     * @param imageCodeKey
     * @return base64图片值
     */
    @PostMapping("/imageCode/{imageCodeKey}")
    public String imageCode(@PathVariable("imageCodeKey")String imageCodeKey){
        System.out.println(imageCodeKey);
        return verifycodeService.getImageCode(imageCodeKey);
    }
    @PostMapping("/sendSmsCode")
    public AjaxResult sendSmsCode(@RequestBody Map<String,String> params){
        return verifycodeService.sendSmsCode(params);
    }
}

5.工具类

public class VerifyCodeUtils {
    //使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
    public static final String VERIFY_CODES = "123456789ABCDEFGHJKLMNPQRSTUVWXYZ";
    private static Random random = new Random();


    /**
     * 使用系统默认字符源生成验证码
     *
     * @param verifySize 验证码长度
     * @return
     */
    public static String generateVerifyCode(int verifySize) {
        return generateVerifyCode(verifySize, VERIFY_CODES);
    }

    /**
     * 使用指定源生成验证码
     *
     * @param verifySize 验证码长度
     * @param sources    验证码字符源
     * @return
     */
    public static String generateVerifyCode(int verifySize, String sources) {
        if (sources == null || sources.length() == 0) {
            sources = VERIFY_CODES;
        }
        int codesLen = sources.length();
        Random rand = new Random(System.currentTimeMillis());
        StringBuilder verifyCode = new StringBuilder(verifySize);
        for (int i = 0; i < verifySize; i++) {
            verifyCode.append(sources.charAt(rand.nextInt(codesLen - 1)));
        }
        return verifyCode.toString();
    }

    /**
     * 输出指定验证码图片流
     *
     */
    public static void outputImage(int w, int h, OutputStream os, String code) throws IOException {
        int verifySize = code.length();
        BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Random rand = new Random();
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        Color[] colors = new Color[5];
        Color[] colorSpaces = new Color[]{Color.WHITE, Color.CYAN,
                Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
                Color.PINK, Color.YELLOW};
        float[] fractions = new float[colors.length];
        for (int i = 0; i < colors.length; i++) {
            colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
            fractions[i] = rand.nextFloat();
        }
        Arrays.sort(fractions);

        g2.setColor(Color.GRAY);// 设置边框色
        g2.fillRect(0, 0, w, h);

        Color c = getRandColor(200, 250);
        g2.setColor(c);// 设置背景色
        g2.fillRect(0, 2, w, h - 4);

        //绘制干扰线
        Random random = new Random();
        g2.setColor(getRandColor(160, 200));// 设置线条的颜色
        for (int i = 0; i < 20; i++) {
            int x = random.nextInt(w - 1);
            int y = random.nextInt(h - 1);
            int xl = random.nextInt(6) + 1;
            int yl = random.nextInt(12) + 1;
            g2.drawLine(x, y, x + xl + 40, y + yl + 20);
        }

        // 添加噪点
        float yawpRate = 0.05f;// 噪声率
        int area = (int) (yawpRate * w * h);
        for (int i = 0; i < area; i++) {
            int x = random.nextInt(w);
            int y = random.nextInt(h);
            int rgb = getRandomIntColor();
            image.setRGB(x, y, rgb);
        }

        shear(g2, w, h, c);// 使图片扭曲

        g2.setColor(getRandColor(100, 160));
        int fontSize = h - 4;
        Font font = new Font("Algerian", Font.ITALIC, fontSize);
        g2.setFont(font);
        char[] chars = code.toCharArray();
        for (int i = 0; i < verifySize; i++) {
            AffineTransform affine = new AffineTransform();
            affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize / 2, h / 2);
            g2.setTransform(affine);
            g2.drawChars(chars, i, 1, ((w - 10) / verifySize) * i + 5, h / 2 + fontSize / 2 - 10);
        }

        g2.dispose();
        ImageIO.write(image, "jpg", os);
    }

    private static Color getRandColor(int fc, int bc) {
        if (fc > 255)
            fc = 255;
        if (bc > 255)
            bc = 255;
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc + random.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static int getRandomIntColor() {
        int[] rgb = getRandomRgb();
        int color = 0;
        for (int c : rgb) {
            color = color << 8;
            color = color | c;
        }
        return color;
    }

    private static int[] getRandomRgb() {
        int[] rgb = new int[3];
        for (int i = 0; i < 3; i++) {
            rgb[i] = random.nextInt(255);
        }
        return rgb;
    }

    private static void shear(Graphics g, int w1, int h1, Color color) {
        shearX(g, w1, h1, color);
        shearY(g, w1, h1, color);
    }

    private static void shearX(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(2);

        boolean borderGap = true;
        int frames = 1;
        int phase = random.nextInt(2);

        for (int i = 0; i < h1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(0, i, w1, 1, (int) d, 0);
            if (borderGap) {
                g.setColor(color);
                g.drawLine((int) d, i, 0, i);
                g.drawLine((int) d + w1, i, w1, i);
            }
        }

    }

    private static void shearY(Graphics g, int w1, int h1, Color color) {

        int period = random.nextInt(40) + 10; // 50;

        boolean borderGap = true;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < w1; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase)
                    / (double) frames);
            g.copyArea(i, 0, 1, h1, 0, (int) d);
            if (borderGap) {
                g.setColor(color);
                g.drawLine(i, (int) d, i, 0);
                g.drawLine(i, (int) d + h1, i, h1);
            }

        }

    }

    /**
     * 获取随机验证码及其加密图片
     *
     */
    public static String VerifyCode(int w, int h, int size) throws IOException {
        BASE64Encoder encoder = new BASE64Encoder();
        String code = generateVerifyCode(size).toLowerCase();
        ByteArrayOutputStream data = new ByteArrayOutputStream();
        outputImage(w, h, data, code);
        return encoder.encode(data.toByteArray());
    }

    public static void main(String[] args) throws  Exception{
        System.out.println(VerifyCode(100, 30, 6));

    }
}

6.入口类

@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class UserService2050Application {
    public static void main(String[] args) {
        SpringApplication.run(UserService2050Application.class,args);
    }
}

7.config

MybatisPlusConfig

//Spring boot方式
@EnableTransactionManagement
@Configuration
@MapperScan("com.sx.mapper")
public class MybatisPlusConfig {

    /**
     * 分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        return new PaginationInterceptor();
    }
}

Swagger2

@Configuration
@EnableSwagger2
public class Swagger2 {
 
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //对外暴露服务的包,以controller的方式暴露,所以就是controller的包.
                .apis(RequestHandlerSelectors.basePackage("cn.itsource.controller"))
                .paths(PathSelectors.any())
                .build();
    }


    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("用户中心api")
                .description("用户中心服务接口文档说明")
                .contact(new Contact("yhptest", "", "yhp@itsource.cn"))
                .version("1.0")
                .build();
    }

}

8.配置文件

application.yml

spring:
  application:
    name: hrm-user

bootstrap.yml

spring:
  profiles:
    active: dev
  cloud:
    config:
      name: application-user #github上面名称
      profile: ${spring.profiles.active} #环境 java -jar -D xxx jar
      label: master #分支
      discovery:
        enabled: true #从eureka上面找配置服务
        service-id: hrm-config-server #指定服务名
      #uri: http://127.0.0.1:1299 #配置服务器 单机配置
eureka: #eureka不能放到远程配置中
  client:
    service-url:
      defaultZone: http://localhost:1010/eureka  #告诉服务提供者要把服务注册到哪儿 #单机环境
  instance:
    prefer-ip-address: true #显示客户端真实ip

zuul网关读取的配置文件
application-user-dev.yml

server:
  port: 2050
spring:
  application:
    name: hrm-user
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/hrm-user
    username: root
    password: 123456
mybatis-plus:
  mapper-locations: classpath:com/sx/mapper/*Mapper.xml
  type-aliases-package: com.sx.domain,com.sx.query

公共模块

在生成那个随机码的时候要将前台传过来的imageCodeKey作为key存放验证到redis中,方便后面来验证验证码输入是否正确
所以要在公共模块的client接口中添加一个方法

    @PostMapping("/time")
    AjaxResult addForTime(@RequestParam(value = "key",required = true) String key
            ,@RequestParam(value = "value",required = true) String value,@RequestParam(value = "time",required = true)Integer time);

在实现类中实现

@Override
            public AjaxResult addForTime(String key, String value, Integer time) {
                return  AjaxResult.me().setSuccess(false).setMessage("redis调用失败");
            }

RedisController

  @PostMapping("/time")
    AjaxResult addForTime(@RequestParam(value = "key",required = true) String key
            ,@RequestParam(value = "value",required = true) String value,@RequestParam(value = "time",required = true)Integer time){
        try
        {
            RedisUtils.INSTANCE.set(key,value,time);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("添加失败");
        }
    }

RedisUtils

 public void set(String key, String value, Integer time) {
        Jedis jedis = getSource();
        // SETEX KEY_NAME TIMEOUT VALUE 第一个是key值 第二个是过期时间 第三个是值
        jedis.setex(key,time,value);
        closeSource(jedis);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值