Spring Boot 实战指南(三):配置事务,整合Elasticsearch、Swagger、Redis、RabbitMQ

一、配置事务

依赖

        <!-- 事务管理依赖以下二选一即可-->
        <!-- 用来开启事务使用 但是mybatis-plus-boot-starter默认引入了sprint-tx -->
<!--        <dependency>-->
<!--            <groupId>org.springframework</groupId>-->
<!--            <artifactId>spring-tx</artifactId>-->
<!--        </dependency>-->

        <!-- springboot整合的事务开启依赖,无论是mybatis或是mybatis-plus都适用 -->
<!--        <dependency>-->
<!--            <groupId>org.springframework.boot</groupId>-->
<!--            <artifactId>spring-boot-starter-aop</artifactId>-->
<!--        </dependency>-->

使用注解

在启动类上添加注解:

@EnableTransactionManagement //开启事务

在需要开启事务的类或者方法上使用注解,前者表示该类的所有方法都开启事务,后者表示只对具体的方法开启事务:

@Transactional(rollbackFor = Exception.class)

如果括号里不带参数表示仅在遇到运行时异常时才回滚,而写了rollbackFor = Exception.class表示遇到非运行时异常也回滚。

二、Elasticsearch

官方文档
Elasticsearch教程

自己搭建了一个简单的demo,仓库在这里,可以直接运行,不过需要自行安装Elasticsearch7.16.3并在application.yml改一下url。

创建项目

用spring initializr 快速搭建一个项目,sdk选的1.8,java版本是8。

spring boot版本选择2.7.x。

勾选这些依赖:

在这里插入图片描述

配置maven

file > settings > build,execution,deployment > build tools > maven

在这里插入图片描述

完善依赖

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>tracy</groupId>
    <artifactId>claimnet-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>claimnet-client</name>
    <description>claimnet客户端</description>
    <properties>
        <java.version>8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

es连接配置

application.yml

spring:
  elasticsearch:
    rest:
      uris: http://es服务器ip:9200

实体映射

package tracy.claimnetclient.entity;

import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.io.Serializable;

@Data
@Document(indexName = "text",createIndex = false) //如果Elasticsearch库中原本不存在这个索引的数据,这里可以写true
public class Text implements Serializable {
   
    @Id //将下面这个属性标记为id
    @Field(name = "id",type = FieldType.Text)
    String id;
    @Field(name = "application_no",type = FieldType.Text)
    String applicationNo;
    @Field(name = "content",type = FieldType.Text)
    String content;
    @Field(name = "date",type = FieldType.Text)
    String date;
    @Field(name = "entity",type = FieldType.Text)
    String entity;
    @Field(name = "feature",type = FieldType.Text)
    String feature;
}

注意,这些属性和Elasticsearch数据库中对应文档中的属性是一一对应的。

repository

ElasticsearchRepository中提供了很多线程的方法,可以满足简单的增删改查需求:

package tracy.claimnetclient.repository;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import tracy.claimnetclient.entity.Text;
import java.util.List;

public interface TextRepository extends ElasticsearchRepository<Text,String> {
   //这里的String表示id的类型
	//PageRequest用来实现分页查询
    List<Text> findTextsByIdOrApplicationNoOrContent(String id, String app, String keyword, PageRequest pageRequest);
}

service

接口:

package tracy.claimnetclient.service;

import tracy.claimnetclient.entity.Text;
import tracy.claimnetclient.util.PairResult;

import java.util.List;

public interface TextService {
   
    List<Text> text(String keyword,
                    Integer curPage,
                    Integer pageSize);
}

实现:

package tracy.claimnetclient.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import tracy.claimnetclient.entity.Text;
import tracy.claimnetclient.repository.TextRepository;
import tracy.claimnetclient.util.PairResult;

import java.util.Arrays;
import java.util.List;

@Service
public class TextServiceImpl implements TextService{
   
    @Autowired
    private TextRepository textRepository;

    @Override
    public List<Text> text(String keyword, Integer curPage, Integer pageSize) {
   
        if(curPage==null)curPage=1;
        if(pageSize==null)pageSize=10;
        return textRepository.findTextsByIdOrApplicationNoOrContent(keyword,keyword,keyword, PageRequest.of(curPage-1,pageSize));
    }
}

controller

package tracy.claimnetclient.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import tracy.claimnetclient.entity.Claim;
import tracy.claimnetclient.entity.Text;
import tracy.claimnetclient.service.ClaimService;
import tracy.claimnetclient.service.TextService;

import java.util.List;

@RestController
@RequestMapping("/search")
public class SearchController {
   
    @Autowired
    private TextService textService;

    @GetMapping("/text/{keyword}")
    public List<Text> text(@PathVariable("keyword")String keyword,
                           Integer curPage,
                           Integer pageSize) {
   
        return textService.text(keyword,curPage,pageSize);
    }
}

【OK】

三、swagger

参考

依赖

 <!-- 引入swagger相关的jar -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>

启动类

类上添加注解@EnableOpenApi

路径匹配配置

application.yml

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher

配置类

package tracy.claimnetclient.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import java.util.ArrayList;

@Configuration
public class SwaggerConfiguration {
   
    @Bean
    public Docket docket() {
   
        //这里要配置controller包
        return new Docket(DocumentationType.OAS_30)
                .select().apis(RequestHandlerSelectors.basePackage("tracy.claimnetclient.controller"))
                .paths(PathSelectors.any()).build()
                .apiInfo(setApiInfo());
    }
    private ApiInfo setApiInfo() {
   
        //作者信息
        Contact contact = new Contact("tracy",
                "https://blog.youkuaiyun.com/Tracycoder?spm=1011.2415.3001.5343",
                "1409568085@qq.com");
        //项目描述
        ApiInfo info = new ApiInfo("Claimnet-client Restful Api", "", "v1.0",
                "https://blog.youkuaiyun.com/Tracycoder?spm=1011.2415.3001.5343"
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TracyCoder123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值