上一篇文章《Java成长之路(一)–SpringBoot基础学习–3种项目创建及热部署》我们说了,如何创建springboot项目。这次我们一起来学习springboot的技术整合。本文中不可能列举所有的技术整合过程,之抛砖引玉,供大家入门学习。
使用SpringBoot整合MyBatis,完成查询所有功能。
实现步骤:
创建SpringBoot工程
勾选依赖坐标
数据库连接信息
创建User表、创建实体UserBean
编写三层架构:Mapper、Service、controller,编写查询所有的方法
配置Mapper映射文件
在application.properties中添加MyBatis配置,扫描mapper.xml和mapper
访问测试地址http://localhost:8080/queryUsers
实现过程:
spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
spring.datasource.password: root
spring.datasource.username: root
spring.datasource.url: jdbc:mysql://127.0.0.1/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
数据库连接地址后加
?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
,不然会报错。
-- ----------------------------
-- Table structure for `user`
-- ---------------------------- DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) DEFAULT NULL,
`password` varchar(50) DEFAULT NULL,
`name` varchar(50) DEFAULT NULL, PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123', '张三'); INSERT INTO `user` VALUES ('2', 'lisi', '123', '李四');
public class User {
private Integer id;
private String username;//用户名
private String password;//密码private String name;//姓名
//getter setter...
//toString
}
使用
@Mapper
标记该类是一个Mapper接口,可以被SpringBoot自动扫描。
package abc.java.mapper;
import abc.java.domain.User;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Repository //注入spring容器
@Mapper
public interface UserMapper {
List<User> findAll();
User findById(Integer id);
void save(User user);
void update(User user);
void delete(Integer id);
}
src/main/resources/mapper
路径下创建UserMapper.xml配置文件<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="abc.java.mapper.UserMapper">
<select id="findAll" resultType="user">
select * from user
</select>
<select id="findById" parameterType="Integer" resultType="user">
select * from user where id = #{id}
</select>
<insert id="save" parameterType="user">
INSERT into user (username,password,name) VALUES (#{username},#{password},#{name})
</insert>
<update id="update" parameterType="user">
update user set username=#{username},password=#{password},name=#{name} where id=#{id}
</update>
<delete id="delete" parameterType="Integer">
delete from user where id=#{id}
</delete>
</mapper>
# 扫描实体
mybatis.type-aliases-package: abc.java.domain
# mapper.xml配置文件路径,mapper目录下的所有以Mapper.xml结尾的文件
mybatis.mapper-locations: classpath:mapper/*Mapper.xml
package abc.java.controller;
import abc.java.domain.User;
import abc.java.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
UserService userService;
/**
* 查询所有
* @return
*/
@RequestMapping("/findAll")
public List<User> findAll() {
return userService.findAll();
}
/**
* 根据id查询
* @param id
* @return
*/
@RequestMapping("/findById")
public User findById(Integer id) {
return userService.findById(id);
}
/**
* 新增
* @param user
*/
@RequestMapping("/save")
public void save(User user) {
userService.save(user);
}
/**
* 修改
* @param user
*/
@RequestMapping("/update")
public void update(User user) {
userService.update(user);
}
/**
* 删除
* @param id
*/
@RequestMapping("/delete")
public void delete(Integer id) {
userService.delete(id);
}
}
实现目标:
SpringBoot整合了Redis之后,实现用户数据查询缓存。
实现步骤:
实现过程:
<!--Redis 依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
# Redis 配置(使用的是默认设置,可以不配置)
spring.redis.host: localhost
spring.redis.port: 6379
/**
* 查询所有
* @return
*/
@RequestMapping("/redis")
public String testRedis() throws JsonProcessingException {
//从redis获取数据
String users = (String) redisTemplate.boundValueOps("userList").get();
if (StringUtils.isEmpty(users)) {
System.out.println("==从数据库中获取用户数据");
//如果为空,则从数据库获取数据
List<User> userList = userService.findAll();
//写入redis
ObjectMapper jsonFormat = new ObjectMapper();
users = jsonFormat.writeValueAsString(userList);
System.out.println("==向redis存储用户数据");
redisTemplate.boundValueOps("userList").set(users);
}
return users;
}
使用SpringBoot开发定时器,每隔5秒输出一个当前时间。实现步骤:
[if !supportLists]1. [endif]开启定时器注解
@SpringBootApplication
@EnableScheduling//开启定时器
public class Day01SpringbootIntergrationApplication {
public static void main(String[] args) {
SpringApplication.run(Day01SpringbootIntergrationApplication.class,args);
}
}
[if !supportLists]2. [endif]配置定时器方法
@Component
public class TimerUtil {
@Scheduled(initialDelay = 1000,fixedRate = 1000)
public void mytask(){
System.out.println(LocalDateTime.now());
}
}
[if !supportLists]3. [endif]测试定时器。
常见远程调用方式:
RPC:(Remote Produce Call)远程过程调用
基于Socket、自定义数据格式、速度快,效率高。
典型应用代表:Dubbo,WebService,ElasticSearch集群间互相调用。
HTTP:网络传输协议
RPC和HTTP的区别:RPC是根据语言API来定义,而不是根据基于网络的应用来定义。
URLConnection(默认方式)
发送Http请求
2. 在项目启动类位置中注册一个RestTemplate对象
@Configuration
public class MyConfiguration {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
@Autowired
private RestTemplate restTemplate;
@Test
public void testREST() {
String url = "http://baidu.com";
String json = restTemplate.getForObject(url, String.class);
System.out.println(json);
}
}
RestTemplate会自动发起请求,接收响应并且帮我们对响应结果进行反序列化