Author:Eric
Version:9.0.0
文章目录
一、引言
1.1 初始化配置
为了使用SSM框架去开发,准备SSM框架的模板配置。
1.2 整合第三方框架
为了Spring整合第三方框架,单独的去编写xml文件。
1.3 后期维护
后期SSM项目后期xml文件特别多,维护xml文件的成本是很高的
1.4 部署工程
SSM工程部署也是很麻烦,依赖第三方的容器
1.5 敏捷式开发
基于Java的SSM开发方式是很笨重,而现在的python,php,NodeJS的敏捷式开发已经盖过Java一头
二、SpringBoot介绍
SpringBoot是由Pivotal团队研发的,SpringBoot并不是一门新技术,只是将之前常用的Spring,SpringMVC,data-jpa等常用的框架封装到了一起,帮助你隐藏这些框架的整合细节,实现敏捷开发。
SpringBoot就是一个工具集。
LOGO |
---|
![]() |
SpringBoot特点:
- SpringBoot项目不需要模板化的配置。
- SpringBoot中整合第三方框架时,只需要导入相应的starter依赖包,就自动整合了。
- SpringBoot默认只有一个.properties的配置文件,不推荐使用xml,后期会采用.java的文件去编写配置信息。
- SpringBoot工程在部署时,采用的是jar包的方式,内部自动依赖Tomcat容器,提供了多环境的配置。
- 后期要学习的微服务框架SpringCloud需要建立在SpringBoot的基础上。
三、SpringBoot快速入门【重点
】
3.1 快速构建SpringBoot
3.1.1 选择构建项目的类型
选择构建项目的类型 |
---|
![]() |
3.1.2 项目的描述
项目的描述 |
---|
![]() |
3.1.3 指定SpringBoot版本和需要的依赖
指定SpringBoot版本和需要的依赖 |
---|
![]() |
3.1.4 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- 将上述内容修改为下面的效果 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
3.1.5 编写了Controller
@RestController
public class TestController {
@GetMapping("/test")
public String test(){
return "Hello SpringBoot!";
}
}
3.1.6 测试
效果 |
---|
![]() |
3.2 SpringBoot的目录结构
3.2.1 pom.xml文件
- 指定了一个父工程: 指定当前工程为SpringBoot,帮助我们声明了starter依赖的版本。
- 项目的元数据:包名,项目名,版本号。
- 指定了properties信息:指定了java的版本为1.8
- 导入依赖:默认情况导入spring-boot-starter,spring-boot-starter-test
- 插件:spring-boot-maven-plugin
3.2.2 .gitignore文件
默认帮我们忽略了一些文件和目录,避免提交到Git仓库中
3.2.3 src目录
-src
-main
-java
-包名
启动类.java # 需要将controller类,放在启动类的子包中或者同级包下
-resources
-static # 存放静态资源的
-templates # 存储模板页面的
application.properties # SpringBoot提供的唯一的配置文件
-test # 只是为了测试用的
3.3 SpringBoot三种启动方式
3.3.1 运行启动类的main方法
运行main方法即可
3.3.2 maven命令
mvn spring-boot:run
IDEA添加一个插件
3.3.3 采用jar包的方式运行
将当前项目打包成一个jar文件,通过按shitf键+鼠标右键选择powershell,并通过java -jar jar文件运行
也可以在cmd窗口启动
四、SpringBoot常用注解【重点
】
4.1 @Configuration和@Bean
之前使用SSM去开发时,在xml文件中编写bean标签,但是SpringBoot不推荐使用xml文件。
@Configuration注解相当于beans标签
@Bean注解相当于bean标签
id=“方法名 | 注解中的name属性(优先级更高)”
class=“方法的返回结果”
@Configuration // 代表当前类是一个配置类
public class UserConfig {
@Bean(name = "user1") // 构建一个实例,放到spring容器中
public User user(){
User user = new User();
user.setId(1);
user.setName("张三");
return user;
}
/*等同于上面的注解
<beans ....> @Configuration
<bean id="user1" class="com.qf.firstspringboot.entity.User" />
</beans>
*/
}
4.2 @SpringBootApplication
@SpringBootApplication就是一个组合注解:
- @SpringBootConfiguration就是@Configuration注解,代表启动类就是一个配置类。
- @EnableAutoConfiguration帮你实现自动装配的,SpringBoot工程启动时,运行一个SpringFactoriesLoader的类,加载META-INF/spring.factories配置类(已经开启的),通过SpringFactoriesLoader中的load方法,以for循环的方式,一个一个加载。
- 好处:无需编写大量的整合配置信息,只需要按照SpringBoot提供好了约定去整合即可。
- 坏处:如果说你导入了一个starter依赖,那么你就需要填写他必要的配置信息。
- 手动关闭自动装配指定内容:@SpringBootApplication(exclude = QuartzAutoConfiguration.class)
- @ComponentScan就相当于<context:component-scan basePackage=“包名” />,帮助扫描注解的。
五、SpringBoot常用配置【重点
】
5.1 SpringBoot的配置文件格式
SpringBoot的配置文件支持properties和yml,甚至他还支持json。
更推荐使用yml文件格式:
yml文件,会根据换行和缩进帮助咱们管理配置文件所在位置
yml文件,相比properties更轻量级一些
yml文件的劣势:
严格遵循换行和缩进
在填写value时,一定要在: 后面跟上空格
5.2 多环境配置
在application.yml文件中添加一个配置项:
spring:
profiles:
active: 环境名
在resource目录下,创建多个application-环境名.yml文件即可
在部署工程时,通过 java -jar jar文件 --spring.profiles.active=环境
5.3 引入外部配置文件信息
和传统的SSM方式一样,通过@Value的注解去获取properties/yml文件中的内容。
如果在yml文件中需要编写大量的自定义配置,并且具有统一的前缀时,采用如下方式
// Java程序
@ConfigurationProperties(prefix = "aliyun")
@Component
@Data
public class AliyunProperties {
private String xxxx;
private ... ...;
}
// 配置文件
aliyun:
xxxx: xxxxxxxxx
...
5.4 热加载
5.4.1 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
5.4.2 settings配置
修改settings中的配置,编译Compiler—勾选自动构建Build project automatically |
---|
![]() |
5.4.3 重新构建工程
build |
---|
![]() |
六、SpringBoot整合Mybatis【重点
】
6.1 xml方式整合Mybatis
xml方式在编写复杂SQL时,更适合
6.1.1 导入依赖。
<!-- mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- druid连接-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
6.1.2 编写配置文件
// 准备实体类
@Data
public class Air implements Serializable {
private Integer id;
private Integer districtId;
private java.util.Date monitorTime;
private Integer pm10;
private Integer pm25;
private String monitoringStation;
private java.util.Date lastModifyTime;
}
// ================================================
@Data
public class District implements Serializable {
private Integer id;
private String name;
}
6.1.3 准备Mybatis
// 1. 接口
public interface AirMapper {
List<Air> findAll();
}
// 2. 在启动类中添加直接,扫描Mapper接口所在的包
@MapperScan(basePackages = "com.qf.firstspringboot.mapper")
// 3. 准备映射文件
<?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="com.qf.firstspringboot.mapper.AirMapper">
<!-- List<Air> findAll();-->
<select id="findAll" resultType="Air">
select * from air
</select>
</mapper>
//4. yml文件
<!-- 添加yml文件配置信息 -->
# mybatis配置
mybatis:
# 扫描映射文件
mapper-locations: classpath:mapper/*.xml
# 配置别名扫描的包
type-aliases-package: com.qf.firstspringboot.entity
configuration:
# 开启驼峰映射配置
map-underscore-to-camel-case: true
# 连接数据库的信息
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///air?serverTimezone=UTC
username: root
password: 123
type: com.alibaba.druid.pool.DruidDataSource
6.1.4 测试。
class AirMapperTest extends FirstSpringbootApplicationTests {
@Autowired
private AirMapper airMapper;
@Test
void findAll() {
List<Air> list = airMapper.findAll();
for (Air air : list) {
System.out.println(air);
}
}
}
6.2 注解方式整合Mybatis
注解方式在编写配置简单,简单SQL推荐使用
6.2.1 创建District的Mapper接口
public interface DistrictMapper {
List<District> findAll();
}
6.2.2 添加Mybatis注解
针对增删改查:@Insert,@Delete,@Update,@Select
还是需要在启动类中添加@MapperScan注解
@Select("select * from district")
List<District> findAll();
@Select("select * from district where id = #{id}")
District findOneById(@Param("id") Integer id);
6.2.3 添加配置
// yml文件
logging:
level:
com.qf.firstspringboot.mapper: DEBUG
6.2.4 测试,查看日志
class DistrictMapperTest extends FirstSpringbootApplicationTests {
@Autowired
private DistrictMapper mapper;
@Test
void findAll() {
List<District> list = mapper.findAll();
for (District district : list) {
System.out.println(district);
}
}
@Test
void findOneById() {
District district = mapper.findOneById(5);
System.out.println(district);
}
}
6.3 SpringBoot整合分页助手
6.3.1 导入依赖
<!-- pageHelper依赖-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.5</version>
</dependency>
6.3.2 测试使用
@Test
public void findByPage(){
//1. 执行分页
PageHelper.startPage(1,5);
//2. 执行查询
List<Air> list = airMapper.findAll();
//3. 封装PageInfo对象
PageInfo<Air> pageInfo = new PageInfo<>(list);
//4. 输出
for (Air air : pageInfo.getList()) {
System.out.println(air);
}
}
七、SpringBoot整合JSP
7.1 需要导入依赖
<!-- JSP核心引擎依赖-->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- JSTL-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
7.2 创建JSP页面
创建webapp以及WEB-INF去存放JSP页面 |
---|
![]() |
7.3 创建Contorller
// Controller
@Controller
public class JspController {
@GetMapping("/index")
public String index(Model model){
model.addAttribute("name","张三");
return "index";
}
}
7.4 配置前缀和后缀
spring:
mvc:
# 视图的前缀和后缀
view:
prefix: /WEB-INF/
suffix: .jsp
八、SpringBoot练习
页面查询客户信息从ES中查询
完成客户模块的增删改,并且同步到ES中。
练习业务图 |
---|
![]() |
8.1 准备工作
1,创建Customer工程,并导入相关的静态资源及实体类
@Data
public class Customer implements Serializable {
private static final long serialVersionUID = 1586034423739L;
/**
* 主键
*
* isNullAble:0
*/
private Integer id;
/**
* 公司名
* isNullAble:1
*/
private String username;
/**
*
* isNullAble:1
*/
private String password;
/**
*
* isNullAble:1
*/
private String nickname;
/**
* 金钱
* isNullAble:1
*/
private Long money;
/**
* 地址
* isNullAble:1
*/
private String address;
/**
* 状态
* isNullAble:1
*/
private Integer state;
}
创建Search工程,并导入es相关的依赖
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.5.4</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.5.4</version>
</dependency>
2,在Search工程的yml文件中配置连接es的ip和端口
elasticsearch:
host: 192.168.206.142
port: 9200
在Search工程中创建一个ElasticsearchConfig配置类
@Configuration
public class ElasticSearchConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private int port;
@Bean
public RestHighLevelClient client(){
HttpHost httpHost = new HttpHost(host,port);
RestClientBuilder builder = RestClient.builder(httpHost);
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
}
在Search工程中导入Customer类
编写测试文件连接es,并创建索引和添加数据
@RunWith(SpringRunner.class)
@SpringBootTest
public class SearchDemoApplicationTests {
@Autowired
private RestHighLevelClient client;
String index = "openapi_customer";
String type = "customer";
@Test
public void createIndex() throws IOException {
//1. 准备关于索引的settings
Settings.Builder settings = Settings.builder()
.put("number_of_shards", 5)
.put("number_of_replicas", 1);
//2. 准备关于索引的结构mappings
XContentBuilder mappings = JsonXContent.contentBuilder()
.startObject()
.startObject("properties")
.startObject("id")
.field("type", "integer")
.endObject()
.startObject("username")
.field("type", "keyword")
.endObject()
.startObject("password")
.field("type", "keyword")
.endObject()
.startObject("nickname")
.field("type", "text")
.endObject()
.startObject("money")
.field("type", "long")
.endObject()
.startObject("address")
.field("type", "text")
.endObject()
.startObject("state")
.field("type", "integer")
.endObject()
.endObject()
.endObject();
//3. 将settings和mappings封装到一个Request对象
CreateIndexRequest request = new CreateIndexRequest(index)
.settings(settings)
.mapping(type, mappings);
//4. 通过client对象去连接ES并执行创建索引
CreateIndexResponse resp = client.indices().create(request, RequestOptions.DEFAULT);
//5. 输出
System.out.println("resp:" + resp.toString());
}
@Test
public void testAddData() throws IOException {
//1. 准备多个json数据
Customer c1 = new Customer();
c1.setId(1);
c1.setUsername("haier");
c1.setPassword("111111");
c1.setNickname("海尔集团");
c1.setMoney(2000000L);
c1.setAddress("青岛");
c1.setState(1);
Customer c2 = new Customer();
c2.setId(2);
c2.setUsername("lianxiang");
c2.setPassword("111111");
c2.setNickname("联想");
c2.setMoney(1000000L);
c2.setAddress("联想");
c2.setState(1);
Customer c3 = new Customer();
c3.setId(3);
c3.setUsername("google");
c3.setPassword("111111");
c3.setNickname("谷歌");
c3.setMoney(1092L);
c3.setAddress("霉果");
c3.setState(1);
ObjectMapper mapper = new ObjectMapper();
String json1 = mapper.writeValueAsString(c1);
String json2 = mapper.writeValueAsString(c2);
String json3 = mapper.writeValueAsString(c3);
//2. 创建Request,将准备好的数据封装进去
BulkRequest request = new BulkRequest();
request.add(new IndexRequest(index, type, c1.getId().toString()).source(json1, XContentType.JSON));
request.add(new IndexRequest(index, type, c2.getId().toString()).source(json2, XContentType.JSON));
request.add(new IndexRequest(index, type, c3.getId().toString()).source(json3, XContentType.JSON));
//3. 用client执行
BulkResponse resp = client.bulk(request, RequestOptions.DEFAULT);
//4. 输出结果
System.out.println(resp.toString());
}
}
8.2 客户模块配置
Customer工程的pom文件中导入durid连接池
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.22</version>
</dependency>
创建CustomerMapper接口及对应的CustomerMapper.xml文件
Customer工程application.yml文件的配置
server:
port: 80
#连接数据库的配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql:///openapi_2001
username: root
password: 123
type: com.alibaba.druid.pool.DruidDataSource
#mybatis的配置
mybatis:
mapper-locations: classpath:mapper/*.xml
type-aliases-package: com.qf.open.customer_demo.entity
configuration:
map-underscore-to-camel-case: true
8.3 查询客户信息(一)
在search模块添加封装数据commons-beanutils的依赖
<!-- 封装数据commons-beanutils的依赖 -->
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
定义SearchService接口及其实现类
public interface SearchService {
String searchByCondition(Map<String,Object> map);
}
编写SearchServiceImpl的实现类
@Service
public class SearchServiceImpl implements SearchService{
@Autowired
private RestHighLevelClient client;
private String index = "openapi_customer";
private String type = "customer";
@Override
public String searchByCondition(Map<String, Object> map) {
//创建request对象
SearchRequest request = new SearchRequest(index);
request.types(type);
//构建查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.sort("id", SortOrder.ASC);
//取值,前端传过来的数据
Object name = map.get("name");
Object state = map.get("state");
if(!StringUtils.isEmpty(name)){
builder.query(QueryBuilders.termQuery("username",name));//es对应的属性名username
}
if(state!=null){
builder.query(QueryBuilders.termQuery("state",state));
}
//页数
Integer page = Integer.parseInt(map.get("page").toString());
Integer limit = Integer.parseInt(map.get("limit").toString());
//查询分页的数据
builder.from((page-1)*limit);//起始下标
builder.size(limit);//每页显示条数
request.source(builder);
try {
//执行查询
SearchResponse searchResponse = client.search(request, RequestOptions.DEFAULT);
TableDataVo<Customer> dataVo = new TableDataVo<>();
List<Customer> data = new ArrayList<>();
//设置总条数
dataVo.setCount(searchResponse.getHits().getTotalHits());
for (SearchHit hit : searchResponse.getHits().getHits()) {
Map<String, Object> sourceAsMap = hit.getSourceAsMap();
//每遍历一条数据,则创建一个对象
Customer customer = new Customer();
//会把map中key对应的value值,赋值给对象的属性,前提条件是key的名称必须和对象的属性一致
BeanUtils.populate(customer,sourceAsMap);
//循环的添加客户对象
data.add(customer);
}
//给vo对象中的集合赋值
dataVo.setData(data);
//把集合转成json数据,并返回
return JSON.toJson(dataVo);
} catch (Exception e) {
e.printStackTrace();
}
//返回结果
return null;
}
}
转json字符串的工具,在Vo包下创建Json类
public class JSON {
public static String toJson(Object value){
ObjectMapper objectMapper = new ObjectMapper();
try {
return objectMapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
e.printStackTrace();
return "";
}
}
}
定义返回json数据的VO对象,可以创建个vo包
@Data
public class TableDataVo<T> {
private Integer code = 0;
private String msg = "";
private Long count;
private List<T> data;
}
8.4 查询客户信息(二)
编写SearchController,并返回json数据
@RestController
@RequestMapping("/search/customer")
public class SearchController {
@Autowired
private SearchService searchService;
@PostMapping(value = "/table",produces = "application/json;charset=utf-8")//避免格式错误
public String table(@RequestBody Map<String,Object> map){
//调用方法
String json = searchService.searchByCondition(map);
//返回结果
return json;
}
}
用postman发送请求,并携带如下json数据
{
"page":1,
"limit":10,
"name":"google"
}
返回的数据
{
"code": 0,
"msg": "",
"count": 1,
"data": [
{
"id": 3,
"username": "google",
"password": "111111",
"nickname": "谷歌",
"money": 1092,
"address": "没过",
"state": 1
}
]
}
8.5 查询客户信息(三)
在customer工程中定义CustomerService接口及实现类
public interface CustomerService {
String findByCondition(Map<String,Object> map);
}
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
private RestTemplate restTemplate;
@Override
public String findByCondition(Map<String, Object> map) {
//准备请求参数和请求头,把请求的参数转成json
String json = JSON.toJson(map);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));//指定类型
//组合 json和httpHeaders,包含数据和请求,设置请求的json数据和数据类型
HttpEntity entity = new HttpEntity(json,httpHeaders);
//通过restTemplate调用search模块,发送请求去请求searchController的接口,返回json数据
String result = restTemplate.postForObject("http://localhost:8080/sys/customer/table", entity, String.class);//String.class是返回类型
return result;
}
}
创建RestTemplateConfig的配置类,并创建RestTemplate对象
能够调用另一个模块search
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class CustomerServiceTest {
@Autowired
private CustomerService customerService;
@Test
public void findByCondition() throws Exception {
Map<String, Object> map = new HashMap<>();
map.put("page",1);
map.put("limit",10);
map.put("name","haier");
String s = customerService.findByCondition(map);
System.out.println(s);
}
}
8.6 查询客户信息(四)
编写CustomerController
@RestController
@RequestMapping("/sys/customer")
public class CustomerController {
@Autowired
private CustomerService customerService;
@GetMapping(value = "/table",produces = "application/json;charset=utf-8")
public String search(@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer limit){
Map<String, Object> map = new HashMap<>();
map.put("page",page);
map.put("limit",limit);
String json = customerService.findByCondition(map);
return json;
}
}
8.7 添加客户信息(一)
在SearchService接口中添加方法
void addCustomer(Customer customer)
SearchServiceImpl类中addCustomer方法的实现
@Slf4j
@Override
public void addCustomer(Customer customer) throws IOException {
//创建request对象
IndexRequest request = new IndexRequest(index,type,customer.getId()+"");
//设置数据
String customerJson = JSON.toJson(customer);
request.source(customerJson, XContentType.JSON);
//client执行添加操作
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
//返回结果
if(!"CREATED".equalsIgnoreCase(response.getResult().toString())){
log.error("【添加文档失败!!】index={},type={},customerid={}"+index,type,customer.getId());
}
}
测试
8.8 添加客户信息(二 )
SearchController类中添加addCustomer方法
@PostMapping("/add")
public void addCustomer(@RequestBody Customer customer) throws IOException {//@RequestBody接收json数据
//调用service,如果有错误,则以抛出异常的方式告知调用者
searchService.addCustomer(customer);
}
8.9 添加客户信息(三)
CustomerMapper添加方法,注意需要在启动类添加MapperScan(“xx”)扫描mapper包
int add(Customer customer);
CustomerMapper.xml文件编写 SQL
<insert id="add" useGeneratedKeys="true" keyProperty="id"><!-- 主键回填,需要将id传到另一个模块, -->
insert into customer
(username,password,nickname,address,money,state)
VALUES
(#{username},#{password},#{nickname},#{address},#{money},#{state})
</insert>
测试能否成功添加客户到数据库
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
public class CustomerMapperTest {
@Autowired
private CustomerMapper customerMapper;
@Test
public void add() throws Exception {
Customer customer = new Customer();
customer.setAddress("haha");
customer.setMoney(10000L);
customer.setNickname("haha");
customer.setPassword("666666");
customer.setUsername("haha");
customer.setState(1);
int result = customerMapper.add(customer);
System.out.println(customer);
System.out.println(customer.getId());
System.out.println(result);
}
}
CustomerService接口添加
void saveCustomer(Customer customer);
CustomerServiceImpl实现类实现方法
@Override
public void saveCustomer(Customer customer) {
//添加customer到数据库
int count = customerMapper.add(customer);
if(count!=1){
log.error("【添加客户信息到数据库失败!】customer={}",customer);
throw new RuntimeException("【添加客户信息到数据库失败!】");
}
//添加customer到es
//准备请求参数和请求头
String json = JSON.toJson(customer);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(MediaType.parseMediaType("application/json;charset=utf-8"));
//组合 json和httpHeaders
HttpEntity entity = new HttpEntity(json,httpHeaders);
//通过restTemplate调用search模块
restTemplate.postForObject("http://localhost:8080/search/customer/add", entity, String.class);
}
测试能否添加客户信息到数据库和es
@Test
public void testSave(){
Customer customer = new Customer();
customer.setAddress("test");
customer.setMoney(10000L);
customer.setNickname("test");
customer.setPassword("666666");
customer.setUsername("test");
customer.setState(1);
customerService.saveCustomer(customer);
}
8.10 添加客户信息(四)
CustomerController添加方法
@PostMapping("/add")
public ResultVO addCustomer(Customer customer){
//添加客户信息
try {
customerService.saveCustomer(customer);
return new ResultVO(true,"添加客户信息成功!");
}catch (RuntimeException e){
e.printStackTrace();
return new ResultVO(true,"添加客户信息失败!");
}
}
个人笔记,思路,仅供参考