新建一个springboot项目(参考我的这一篇文章),选择War,勾选依赖时,按照下图勾选内容
lombok可以简化代码,省去实体类中set、get、toString等冗余的代码等等;
加入mybatis-plus的依赖:
com.baomidou
mybatis-plus-boot-starter
3.1.2
为了规范,这里我采用了版本限定的写法。在工作中,一定要养成良好的代码习惯,不要写成上面那种形式,要按照下面这种方式限定版本号:
3.1.2
com.baomidou
mybatis-plus-boot-starter
${mp.version}
com.baomidou
mybatis-plus-boot-starter
实体层字段是根据聚合技术里面人家第三方接口返回的字段写的!后面有介绍
import lombok.Data;
import java.math.BigInteger;
import java.util.Date;
@Data
@TableName("t_joke")
public class Joker {
private int id;
private String content;
private String hashid;
private BigInteger unixtime;
private Date updatetime;
}
导入lombok依赖之后,我们只需要在实体类上加注解@Data
就可以不用写setget方法、toString方法了,很方便!
需要注意的是,这里的实体类名,成员变量名要和数据库对应,
@TableName("t_joke")
去对应;@TableId
@TableField
@TableField(exist = false)
标识BaseMapper
在这里,我们的mapper层继承了BaseMapper
,在这个方法里封装着各种增删改查!
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xude.joker.entity.Joker;
public interface JokerMapper extends BaseMapper {
}
mapper层写完了!
IService
import com.baomidou.mybatisplus.extension.service.IService;
import com.xude.joker.entity.Joker;
public interface JokerService extends IService {
}
service
的实现层需要继承ServiceImpl
,泛型里两个参数为
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xude.joker.entity.Joker;
import com.xude.joker.mapper.JokerMapper;
import com.xude.joker.service.JokerService;
@Service
public class JokerServiceImpl extends ServiceImpl implements JokerService {
}
import lombok.Data;
@Data
public class Vo {
//返回码
private int code;
//返回的内容
private String msg;
//返回的数据
private T data;
//成功,无数据
public static Vo setOK(String msg) {
Vo vo = new Vo<>();
vo.setCode(200);
vo.setMsg(msg);
vo.setData(null);
return vo;
}
//成功返回的数据
public static Vo setOK(String msg,E obj) {
Vo vo = new Vo<>();
vo.setCode(200);
vo.setMsg(msg);
vo.setData(obj);
return vo;
}
//错误
public static Vo setERROR(String msg) {
Vo vo = new Vo<>();
vo.setCode(400);
vo.setMsg(msg);
vo.setData(null);
return vo;
}
//根据调用时参数是否为true,选择setOK或者setERROR
public static Vo exec(boolean issuc,String msg) {
return issuc ? setOK(msg) : setERROR(msg);
}
}
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xude.joker.entity.Joker;
import com.xude.joker.service.JokerService;
import com.xude.joker.vo.Vo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/joker")
@Api(value = "笑话大全",tags = "笑话大全")
public class JokerController {
@Autowired
private JokerService jokerService;
//新增
@ApiOperation(value = "新增笑话")
@PostMapping("/save.do")
public Vo save(@RequestBody Joker joker) {
return Vo.exec(jokerService.save(joker),"新增");
}
//删除
@ApiOperation(value = "删除笑话")
@DeleteMapping("/del.do/{id}")
public Vo del(@PathVariable int id) {
return Vo.exec(jokerService.removeById(id),"删除");
}
//修改
@ApiOperation(value = "修改笑话")
@PutMapping("/update.do/{id}")
public Vo update(Joker joker) {
return Vo.exec(jokerService.updateById(joker),"修改");
}
//查询
@ApiOperation(value = "查询全部")
@GetMapping("/All.do")
public Vo selectAll() {
return Vo.setOK("OK",jokerService.list());
}
//查询详情
@ApiOperation(value = "查询一个笑话")
@GetMapping("/detail.do/{id}")
public Vo selectAll(@PathVariable int id) {
return Vo.setOK("OK",jokerService.getById(id));
}
//分页查询
@ApiOperation(value = "分页接口")
@GetMapping("/page/{page}/{count}")
public Vo page(@PathVariable int page, @PathVariable int count) {
//Mybatis-Plus的分页插件要想使用,注意不要导错包,还要再启动类加
Page jokerPage = new Page<>(page,count);
return Vo.setOK("OK",jokerService.page(jokerPage));
}
}
新建一个配置类MybatisPlusConfig
:
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@EnableTransactionManagement
@Configuration
@MapperScan("com.xude.joker.mapper")
public class MybatisPlusConfig {
/**
* 分页插件
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//paginationInterceptor.setLimit(你的最大单页限制数量,默认500条,小于0如-1则不受限制);
return paginationInterceptor;
}
}
具体请参看我的另一篇博客Swagger2的使用
java程序请求第三方接口:
HttpClient
——ApacheHttpURLConnection
OKHttp
HttpUrl
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class HttpUtil {
public static String getStr(String url) {
try {
//1. 创建连接对象
URL myUrl = new URL(url);
//2. 获取连接对象
HttpURLConnection httpURLConnection = (HttpURLConnection) myUrl.openConnection();
//3. 设置请求信息
httpURLConnection.setRequestMethod("GET");//get请求
httpURLConnection.setConnectTimeout(5000);//设置超时时间5秒
//4. 发起请求
httpURLConnection.connect();
//5. 验证响应状态码200、304、400、404、500
if (httpURLConnection.getResponseCode() == 200){
//6. 获取响应结果——流!!!
InputStream inputStream = httpURLConnection.getInputStream();
byte[] data = new byte[1024];
int len;
StringBuffer stringBuffer = new StringBuffer();
while ((len=inputStream.read(data)) != -1) {
stringBuffer.append(new String(data,0,len));
}
//7. 关闭流,断开连接
inputStream.close();
httpURLConnection.disconnect();
return stringBuffer.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
//出现异常,则返回null
return null;
}
}
这个类需要的数据是一个Url
,可以根据url通过 流 拿到数据并返回String
类型的字符串
对于本次例子,我是用的第三方接口是聚合工程 https://www.juhe.cn
这里面提供了一些免费的接口,比如笑话大全、天气预报等等
你需要注册账号,添加接口,然后拿到接口的appkey
然后在”接口“中拿到”请求示例“,待会需要传给上一步中的参数(里面的”您申请的KEY“要替换成appkey值!)
在”接口“里,你也可以看到这个接口的详细参数,比如必须给的参数、返回的参数等等
import com.xude.joker.utils.HttpUtil;
import org.junit.Test;
public class ThirdInterfaceTest {
@Test
public void UrlTest() {
String url = "http://v.juhe.cn/joke/content/text.php?key=您申请的KEY&page=1&pagesize=5";
System.out.println("笑话的接口"+ HttpUtil.getStr(url));
}
}
记得替换Key!!!
关于定时任务参考我另一篇博客:SpringBoot之定时任务Spring Task简单的应用
GsonFormat
解析json
数据我们需要的数据是”data“中的数据
这时我们可以利用插件GsonFormat
解析json数据,他需要我们使用idea安装
安装完成之后,新建一个实体类JokeJson
复制得到的那段joke数据(一整套数据),在实体类JokeJson
中组合键alt
+ins
选择GosonFormat
粘贴刚才复制的内容:
这样我们就接到了data数据
JokeTask
类
com.alibaba
fastjson
1.2.7
JokeTask
类import com.alibaba.fastjson.JSON;
import com.xude.joker.entity.JokeJson;
import com.xude.joker.entity.Joker;
import com.xude.joker.service.JokerService;
import com.xude.joker.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class JokeTask {
@Autowired
private JokerService jokerService;
@Scheduled(cron = "30 35 17 * * ?") //每天17:35:30会执行这个定时任务
public void downloadJoke() {
String url = "http://v.juhe.cn/joke/content/text.php?key=您申请的KEY&page=1&pagesize=20";
// System.out.println("笑话的接口"+ HttpUtil.getStr(url));
String json = HttpUtil.getStr(url);
if (json != null) {
JokeJson jokeJson = JSON.parseObject(json,JokeJson.class);
List jokerDataList = jokeJson.getResult().getData();
jokerService.saveBatch(jokerDataList);
}
}
}