Java Send SMS Series restrictions on the number of days sent _java

Source: Internet
Author: User
Tags dateformat static class

In the first two articles, we implemented synchronous/asynchronous texting and restricted the frequency of texting. In this article, we introduce the number of times you limit daily messages to the same user (based on cell phone number and IP)

1. Data table structure

This is where we save the data to the database because we need to record the sending record all day. The data table structure is as follows:

Types are type of verification code, such as registration, resetting passwords, and so on.
The default value for the Sendtime is the current time.

2, limit the number of days sent

Here we need to use the interface and entity classes mentioned in the previous article.

Dailycountfilter.java

public class Dailycountfilter implements Smsfilter {

  private int ipdailymaxsendcount;
  private int mobiledailymaxsendcount;
  Private Smsdao Smsdao;

  Omitted part of the unwanted code

  @Override public
  boolean filter (Smsentity smsentity) {
    if Smsdao.getmobilecount ( Smsentity.getmobile ()) >= Mobiledailymaxsendcount) {return
      false;
    }
    if (Smsdao.getipcount (Smsentity.getip ()) >= Ipdailymaxsendcount) {return
      false;
    }
    Smsdao.saveentity (smsentity);
    return true;
  }



The main code is very simple, first of all, to determine whether the number of sent to the specified mobile phone number to reach the maximum number of days sent, and then determine whether the specified IP request to send the number of times to reach the maximum number. If not, then the mobile phone number, IP and other information sent to the database.

Of course, there is a problem with this class: There may already be other threads saving the new data in determining whether the maximum number of times is exceeded to the storage entity data. The above two judgements are not absolutely accurate.

We can use serialization-level transactions to ensure that no errors occur, but at a very high price. So we don't have to deal with it here. Because we've already implemented a limit on the sending frequency. If you use Frequencyfilter first to filter once and limit the frequency of the transmission, then it is virtually impossible to say the previous question.

There is also a problem: over time, the table will grow larger and the performance of the query is quite poor. We can delete useless data every once in a while. You can also create a table dynamically, and then insert data into the new table.

3, the use of dynamic table

Here we adopt the second scenario: the name of the datasheet is "Sms_ four years _ two months", such as "sms_2016_02". When you insert data, get the table name based on the current time, and then insert it. Also use quartz to generate a datasheet for the next month and next month at 20th # 2 per month:

We first modify the Dailycountfilter class, add a task schedule to this class, and periodically generate the datasheet:

Dailycountfilter.java

On the basis of the above code, add the following code public class Dailycountfilter implements Smsfilter {private Scheduler sched; @Override public void Init () throws schedulerexception {smsdao.createtable (0);//create this month's datasheet smsdao.createtable ( 1);
    Create a datasheet for the next month schedulerfactory SF = new Stdschedulerfactory (); Sched = Sf.getscheduler ();
    Create Quartz container jobdatamap Jobdatamap = new Jobdatamap ();  Jobdatamap.put ("Smsdao", Smsdao); Create the data map//Create Job object that you want to use when you run the task, and the object performs the actual task Jobdetail job = Jobbuilder.newjob (Createsmstablejob.class).

    Usingjobdata (Jobdatamap). Withidentity ("Create SMS Table Job"). Build (); Creates a trigger object that describes the time rule that triggers the execution of the job, such as the 2-point 20th per month here, Crontrigger trigger = Triggerbuilder.newtrigger (). Wit Hidentity ("Create SMS Table Trigger"). Withschedule (Cronschedulebuilder.cronschedule ("0 0 2 20 *?"))

    20th per month, 2. Build ();  Sched.schedulejob (Job, trigger); Registration task and trigger rule sched.start (); Start dispatch} @Override PubLIC void Destroy () {try {sched.shutdown (); The catch (Schedulerexception e) {}} public static class Createsmstablejob implements Job {@Override Publ IC void Execute (Jobexecutioncontext context) throws Jobexecutionexception {Jobdatamap Datamap = Context.getjobdetai
      L (). Getjobdatamap (); Smsdao Smsdao = (Smsdao) datamap.get ("Smsdao"); Obtain the Smsdao object Smsdao.createtable (1); Create a datasheet for next month smsdao.createtable (2);
 Create next month's data table}}

Next, let's look at some of the Smsdao code:

Smsdao.java

public class Smsdao {/** * Create a new log table * * @param monthexcursion offset of the number of months/public void createtable (int month
    Excursion) {String sql = ' CREATE TABLE IF not EXISTS ' + gettablename (monthexcursion) + ' like SMS '; Execute SQL statement}/** * Save smsentity Entity Object */public void saveentity (Smsentity smsentity) {String sql = ' INSERT I
    NTO "+ getnowtablename () +" (Mobile, IP, type) VALUES (?,?,?); Execute SQL statement}/** * Get specified number of SMS requests sent today * * @param mobile subscriber Phone number * @return The number of requests to send SMS today/public long G Etmobilecount (String mobile) {String sql = SELECT count (ID) from "+ getnowtablename () +" WHERE mobile=?
    and Time >= curdate () ";  Executes the SQL statement, returns the query result}//omits the Getipcount method/** * Get the name of the table you are using/private String Getnowtablename () {return
  Gettablename (0);

  Private DateFormat DateFormat = new SimpleDateFormat ("yyyy_mm"); /** * Gets the number of monthexcursion of the table name * * @param monthexcursion offset of the current offset of the month *@return table name for the corresponding month/private String gettablename (int monthexcursion) {Calendar calendar = calendar.getinstance ();
    Calendar.add (Calendar.month, monthexcursion);
    Date date = Calendar.gettime ();
  Return "SMS_" + dateformat.format (date);

 }

}

A prerequisite for a successful CreateTable method in Smsdao is the existence of an SMS data table. The CreateTable method copies the structure of the SMS table to create a new datasheet.

We reserve the data to send SMS (cell phone number, IP, time, etc.), rather than delete directly, because you may need to analyze the data, get the information we want, such as judge the arrival rate of SMS, whether someone malicious send text messages. May even get an unexpected "surprise".

The above is the entire content of this article, I hope you can continue to pay attention to.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.