项目搭建 Day08 -spring获取上下文工具,阿里云短信接入

项目练习 / 2021-12-30

mall Day08

mall-learning

spring上下文获取工具类

方便读取在applicatison配置文件的 value

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
 * @Description:
 * @author: zwy
 * @date: 2021年12月30日 14:11
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {

	/**
	 * 上下文对象实例
	 */
	private static ApplicationContext applicationContext;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringContextUtils.applicationContext = applicationContext;
	}

	/**
	 * 获取applicationContext
	 *
	 * @return
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}

	/**
	  * 获取HttpServletRequest
	 */
	public static HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}


	public static String getOrigin(){
		HttpServletRequest request = getHttpServletRequest();
		return request.getHeader("Origin");
	}

	/**
	 * 通过name获取 Bean.
	 *
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}

	/**
	 * 通过class获取Bean.
	 *
	 * @param clazz
	 * @param       <T>
	 * @return
	 */
	public static <T> T getBean(Class<T> clazz) {
		return getApplicationContext().getBean(clazz);
	}

	/**
	 * 通过name,以及Clazz返回指定的Bean
	 *
	 * @param name
	 * @param clazz
	 * @param       <T>
	 * @return
	 */
	public static <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}
}

配置短信config

读取配置文件的密钥

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Description: TODO
 * @author: zwy
 * @date: 2021年12月30日 14:03
 */
@Component
@Data
public class SMSconfig {
    @Value("${zwy.oss.secretKey}")
    public String secretKey;

    @Value("${zwy.oss.accessKey}")
    public String accessKey;
}

短信发送

导入阿里云pom

        <!--        阿里云短信发送服务-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.16</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>dysmsapi20170525</artifactId>
            <version>2.0.8</version>
        </dependency>

发送短信关键方法

import cn.hutool.json.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.teaopenapi.models.Config;
import com.zwy.mall.tiny.common.enums.SMSEnum;
import com.zwy.mall.tiny.common.utils.SpringContextUtils;
import com.zwy.mall.tiny.config.alicloud.SMSconfig;
import lombok.extern.log4j.Log4j2;

/**
 * @Description:
 * @author: zwy
 * @date: 2021年12月30日 13:47
 */
@Log4j2
public class SMS {

    /**
     * 使用AK&SK初始化账号Client
     *
     * @return Client
     * @throws Exception
     */
    public static Client createClient() throws Exception {

        SMSconfig smSconfig = SpringContextUtils.getBean(SMSconfig.class);
        log.info("smSconfig配置:{}", smSconfig.toString());
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(smSconfig.getAccessKey())
                // 您的AccessKey Secret
                .setAccessKeySecret(smSconfig.getSecretKey());
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }

    public static void sms(String phone, JSONObject templateParam, SMSEnum smsEnum) {
        //初始化client账号
        Client client = null;
        try {
            client = SMS.createClient();
        } catch (Exception e) {
            log.error("初始化阿里云短信client账号失败");
        }
        //判断参数中是否有对应键
        for (String s : smsEnum.getKeys().split(",")) {
            if (!templateParam.containsKey(s)) {
                log.info("缺少指定键   :{}" + s);
                return;
            }
            ;
        }//发送短信
        log.info(templateParam.toString());
        SendSmsRequest sendSmsRequest = new SendSmsRequest()
                .setPhoneNumbers(phone)
                .setSignName(smsEnum.getSignName())
                .setTemplateCode(smsEnum.getTemplateCode())
                .setTemplateParam(templateParam.toString());
        // 复制代码运行请自行打印 API 的返回值
        try {
            client.sendSms(sendSmsRequest);
        } catch (Exception e) {
            log.error("短信发送失败检查短信内容");
            e.printStackTrace();
        }
    }
}