Micro projects: take you step by step using SpringBoot entry (a)

Recently holiday, rest of the time did not forget to write a small program to play.
If you need to manually do the project with a friend and I can do it with this little project.
Do what arbitrary. Haha week will do.
***

Development environment

  • JDK1.8
  • JetBrain InteliJ

Fool-start the project

NewProject then click Open and then been next Spring Initializr

Here determine the package name of the class is good

Click here goes nothing, directly next on the list

Here we can see the project built up.

We direct point start, you will be able to project up and running.

OK, now we've had the SpringBoot to build.

I will its open source, so we need to put this project Github above.

First, share it
and intuitively point has been down on it.

In this project address: https: //github.com/GodofOrange/anonymous

I will continue to update the article.
If interested students can give a star

Project requirements

I would like to take advantage of the National Day to make an anonymous pour out of trouble APP, in fact, the whole idea is quite simple to implement, but if you only use mysql it does not make sense, so I'll use jpa + redis + kafka + ngnix assembled a high-availability rear end.

The entire project it, I intend to use agile development methods, little by little integrated into the project inside.

SpringBoot + JPA persistence to do

MYSQL environment, we believe we will be there, and that gives me direct data sheet (note ORM technology do not build table)

id title content update summary hot
BIGINT varchar(255) LONGTEXT TIMESTAMP TEXT BIGINT

Database creation script:

CREATE DATABASE anonymous DEFAULT CHARSET utf8mb4;

OK, now the database has been built up. So we are going to rely on it to import the JPA.

Introduce the following files in the pom file.

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

Then modify the configuration file.

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/anonymous?serverTimezone=UTC&useSSL=true&allowMultiQueries=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.jpa.show-sql=true
spring.jpa.database=mysql
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.MySQL57InnoDBDialect

Then start to see whether the error.

If there is no error, it will be the normal exit all OK.

Let's create a table

New Class Wall.java

package cn.baldorange.anonymous.entity;

import javax.persistence.*;
import java.util.Date;

@Entity(name = "wall")
public class Wall {
    public Wall(){

    }
    public Wall(String title, String content, Date up_time, String summary, String hot) {
        this.title = title;
        this.content = content;
        this.up_time = up_time;
        this.summary = summary;
        this.hot = hot;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id",columnDefinition="BIGINT COMMENT '主键,自动生成'")
    private String id;
    @Column(name = "title",columnDefinition="VARCHAR(255)")
    private String title;
    @Column(name = "content",columnDefinition="LONGTEXT")
    private String content;
    @Column(name = "up_time",columnDefinition="TIMESTAMP")
    private Date up_time;
    @Column(name = "summary",columnDefinition="TEXT")
    private String summary;
    @Column(name = "hot",columnDefinition = "BIGINT")
    private String hot;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Date getUp_time() {
        return up_time;
    }

    public void setUp_time(Date up_time) {
        this.up_time = up_time;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public String getHot() {
        return hot;
    }

    public void setHot(String hot) {
        this.hot = hot;
    }

    @Override
    public String toString() {
        return "Wall{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", up_time=" + up_time +
                ", summary='" + summary + '\'' +
                ", hot='" + hot + '\'' +
                '}';
    }
}

New Interface

package cn.baldorange.anonymous.repository;

import cn.baldorange.anonymous.entity.Wall;
import org.springframework.data.jpa.repository.JpaRepository;

public interface WallRepo extends JpaRepository<Wall,String> {

}

SpringTest file

package cn.baldorange.anonymous;

import cn.baldorange.anonymous.entity.Wall;
import cn.baldorange.anonymous.repository.WallRepo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AnonymousApplicationTests {
    @Autowired
    WallRepo wallRepo;
    @Test
    public void contextLoads() {
        wallRepo.save(new Wall("测试","文章",new Date(),"摘要","0"));
       System.out.println(wallRepo.findById("1"));
    }

}

Run results are shown below:

DAO layer this over.

We pushed up directly after Commit

This completes the code once submitted


Here are SpringBoot integrated solutions other projects. As can be extended by reference


swagger introduced

Swagger is a tool interface documentation, in accordance with Swagger 0 configuration can develop interface. Note, however, Swagger is based SpringBoot1.47 version developed, but SpringBoot now basically is 2+.
If you want to choose restful support, only to withdraw the SpringBoot 1+ version.
***

maven introduced

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

Swagger configuration documentation

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class swaggerConfig {
    @Bean
    Docket docket(){
        return new Docket(DocumentationType.SWAGGER_2)
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.any())
                .build()
                .apiInfo(new ApiInfoBuilder().description("项目").build());
    }
}

Interface Configuration

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.just.computer.mathproject.Entity.Advertisement;
import org.just.computer.mathproject.Service.AdvertisementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@Api(tags ="广告")
@RequestMapping("/Advertisement/")
public class AdvertisementController {
    @Autowired
    AdvertisementService advertisementService;

    @ApiOperation(value ="获得所有广告")
    @GetMapping("/getAllAdvertisement")
    public List<Advertisement> getAllAdvertisement(){
        return advertisementService.getAllAdvertisement();
    }
    @ApiOperation(value = "添加广告")
    @GetMapping("/addAdvertisement")
    public Boolean getAllAdvertisement(@RequestParam String img, @RequestParam String href){
        try {
            advertisementService.addAdvertisement(img,href);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    @ApiOperation(value = "删除广告")
    @GetMapping("/deleteAdvertisement")
    public Boolean deleteAdvertisementById(Integer id){
       try{
           advertisementService.deleteAdvertisementById(id);
           return true;
       }catch (Exception e){
           return false;
       }
    }
}

After the visit to run locally here to visit
or to ip: port /swagger-ui.html
results are as follows

SpringBoot introduced websocket


maven dependence

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

WebSocketConfig profile

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
    @Override
    public void configureMessageBroker(MessageBrokerRegistry config){
        config.enableSimpleBroker("/topic");
        config.setApplicationDestinationPrefixes("/app");
    }
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry){
        registry.addEndpoint("/chat").setAllowedOrigins("*").withSockJS();
    }
}

After configuring basically do not do other configured
setAllowedOrigins () function for the cross-domain

Then the Controller

import org.just.computer.mathproject.Bean.Message;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

import java.security.Principal;
import java.util.Date;

@Controller
public class GreetingController {
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public Message greeting(String content, Principal pl) throws Exception{
        Message message = new Message();
        message.setContent(content.substring(1,content.length()-1));
        message.setData(new Date().toString());
        message.setName(pl.getName());
        return message;
    }
}

Principal here for SpringSecurity knowledge in order to obtain a user name through the session.
So far, SpringBoot configuration has been gone

Vue by stompClient use webSocket


package.json

"dependencies": {
    "@tinymce/tinymce-vue": "^3.0.1",
    "axios": "^0.19.0",
    "echarts": "^4.2.1",
    "element-ui": "^2.11.1",
    "net": "^1.0.2",
    "nprogress": "^0.2.0",
    "sockjs-client": "^1.4.0",
    "stompjs": "^2.3.3",
    "tinymce": "^4.8.5",
    "tinymce-vue": "^1.0.0",
    "vue": "^2.5.2",
    "vue-axios": "^2.1.4",
    "vue-echarts": "^4.0.3",
    "vue-router": "^3.0.1",
    "vue-stomp": "0.0.5"
  }

Be sure to have a filling vue-stomp sockjs-client stompjs these three
want to use directly into place.

import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'

following complete code vue

<template>
  <div>
    <input type="text" v-model="text">
    <button @click="sendMessage">发送消息</button>
    <div class="bubble">
    </div>
    <div>
      <div v-for="(data,key) in datas" :key="key">
        {{data.content}}
      </div>
    </div>
  </div>
</template>
<script>
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
export default {
  name: 'ChatRoom',
  data () {
    return {
      text: '',
      datas: [],
      stompClient: null
    }
  },
  mounted () {
    if ('WebSocket' in window) {
      this.initWebSocket()
    } else {
      alert('当前浏览器 Not support websocket')
    }
  },
  methods: {
    sendMessage () {
      this.stompClient.send('/app/hello', JSON.stringify(this.text), {})
    },
    initWebSocket () {
      this.connection()
    },
    connection () {
      const socket = new SockJS(this.$baseUrl + '/chat')
      this.stompClient = Stomp.over(socket)
      this.stompClient.connect({}, (frame) => {
        this.stompClient.subscribe('/topic/greetings', (greeting) => {
          console.log(JSON.parse(greeting.body))
          this.datas.push(JSON.parse(greeting.body))
        })
      })
    }
  }
}
</script>

<style scoped>
</style>

Note that in this line of code this.stompClient.send ( '/ app / hello' , JSON.stringify (this.text), {}) {} positions, some versions may be reversed.
Run results are shown below

Guess you like

Origin www.cnblogs.com/godoforange/p/11613521.html