记录SpringBoot整合Eureka,springsecurity,swagger,mybatisplus

一、项目搭建所需

1.创建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.2.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.springboot</groupId>
    <artifactId>springsecurity1</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springsecurity1</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- mybatis plus 代码生成器依赖 -->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- 代码生成器模板 -->
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <version>2.1.5.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>
`
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

2.application.yml

server:
  port: 10001
eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    serviceUrl:
      defaultZone: http://localhost:10001/eureka
#security:
 # basic:
  #  enabled: false
spring:
  #数据库配置
  datasource:
    url: jdbc:mysql://localhost:3306/test1?useSSL=false&serverTimezone=UTC
    username: root
    password: 123456
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver

#mybatisplus配置数据库的字段含下划线自动映射实体类驼峰模式
mybatis:
  configuration:
  map-underscore-to-camel-case: true

#mybatisplus配置输出sql语句
mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3.用于测试的实体类Book

package com.springboot.springsecurity1.bean;

import java.io.Serializable;
import java.util.Date;

public class Book implements Serializable {
    private int bookId;
    private String bookName;
    private String picture;
    private int ownerId;
    private int currentOwnerId;
    private String author;
    private String description;
    private Date createdTime;
    private Date  updateTime;

    public Book() {
    }

    public int getBookId() {
        return bookId;
    }

    public void setBookId(int bookId) {
        this.bookId = bookId;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public String getPicture() {
        return picture;
    }

    public void setPicture(String picture) {
        this.picture = picture;
    }

    public int getOwnerId() {
        return ownerId;
    }

    public void setOwnerId(int ownerId) {
        this.ownerId = ownerId;
    }

    public int getCurrentOwnerId() {
        return currentOwnerId;
    }

    public void setCurrentOwnerId(int currentOwnerId) {
        this.currentOwnerId = currentOwnerId;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getCreatedTime() {
        return createdTime;
    }

    public void setCreatedTime(Date createdTime) {
        this.createdTime = createdTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    @Override
    public String toString() {
        return "Book{" +
                "bookId=" + bookId +
                ", bookName='" + bookName + '\'' +
                ", picture='" + picture + '\'' +
                ", ownerId=" + ownerId +
                ", currentOwnerId=" + currentOwnerId +
                ", author='" + author + '\'' +
                ", description='" + description + '\'' +
                ", createdTime=" + createdTime +
                ", updateTime=" + updateTime +
                '}';
    }
}

4.bookDao

package com.springboot.springsecurity1.dao;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.springboot.springsecurity1.bean.Book;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import java.util.List;

@Component
public interface BookDao extends BaseMapper<Book> {


}

5.bookService接口

public interface BookService{
    /***
     * 根据书本编号查询书本信息
     * @param id  书本编号
     * @return
     */
    Book getBookById(int id);

    /**
     * 根据书名进行模糊查询书本信息
     * @param book 书本实体
     * @return
     */
    List<Book> getBooksByName(Book book);

    /**
     * 通过书本的名称或者描述进行模糊查询
     * @param book 书本实体
     * @return
     */
    List<Book> getBookByFuzzy(Book book);
}

6.bookServiceImpl实现类

@Service
public class BooServiceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

    @Override
    public List<Book> getBookByFuzzy(Book book) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(!StringUtils.isEmpty(book.getBookName()),"book_name",book.getBookName())
                .or().like(!StringUtils.isEmpty(book.getDescription()),"description",book.getDescription());
        return bookDao.selectList(queryWrapper);
    }

    @Override
    public List<Book> getBooksByName(Book book) {
        QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(true, "book_name", book.getBookName());
        List<Book> list = bookDao.selectList(queryWrapper);
        return list;
    }

    @Override
    public Book getBookById(int id) {
        QueryWrapper<Book> wrapper = new QueryWrapper<Book>();
        wrapper.eq("book_id",id);
        return bookDao.selectOne(wrapper);

    }
}

7.Controller

@RequestMapping("book")
@RestController
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping("/get")
    public Book Search(int bookId){
        Book book = bookService.getBookById(bookId);
        System.out.println(book);
        return book;
    }

    @RequestMapping("/gets")
    public List<Book> likeSearch(Book book){
        List<Book> list= bookService.getBooksByName(book);
        System.out.println(list.size());
        for(Book b : list){
            System.out.println(b);
        }
        return list;
    }

    @RequestMapping("getsf")
    public List<Book> getBookByFuzzy(Book book){
        List<Book> list = bookService.getBookByFuzzy(book);
        for(Book b : list){
            System.out.println(b);
        }
        return list;
    }
}

8.启动类

package com.springboot.springsecurity1;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;

//@ComponentScan({"com.springboot.springsecurity1","com.springboot.springsecurity1.controller"})
@SpringBootApplication
@EnableFeignClients // 开启Feign功能
@EnableEurekaServer
@MapperScan("com.springboot.springsecurity1.dao")
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
}

9.用postman测试

控制台打印信息:

com.springboot.springsecurity1.App
2020-08-05 13:25:07.735  INFO 16764 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.2.4.RELEASE)

2020-08-05 13:25:09.836  INFO 16764 --- [           main] com.springboot.springsecurity1.App       : No active profile set, falling back to default profiles: default
2020-08-05 13:25:11.091  WARN 16764 --- [           main] o.s.boot.actuate.endpoint.EndpointId     : Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2020-08-05 13:25:11.260  INFO 16764 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=0cfe3cd8-9a9c-3ccf-ac37-8005bccfe9ef
2020-08-05 13:25:11.468  INFO 16764 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-08-05 13:25:11.493  INFO 16764 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2020-08-05 13:25:11.839  INFO 16764 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 10001 (http)
2020-08-05 13:25:11.850  INFO 16764 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2020-08-05 13:25:11.850  INFO 16764 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.30]
2020-08-05 13:25:11.982  INFO 16764 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2020-08-05 13:25:11.982  INFO 16764 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2115 ms
2020-08-05 13:25:12.110  WARN 16764 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2020-08-05 13:25:12.110  INFO 16764 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2020-08-05 13:25:12.124  INFO 16764 --- [           main] c.netflix.config.DynamicPropertyFactory  : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@47e51549
2020-08-05 13:25:12.554  INFO 16764 --- [           main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
2020-08-05 13:25:13.011  INFO 16764 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
2020-08-05 13:25:14.736  INFO 16764 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2020-08-05 13:25:15.000  INFO 16764 --- [           main] c.s.j.s.i.a.WebApplicationImpl           : Initiating Jersey application, version 'Jersey: 1.19.1 03/11/2016 02:08 PM'
2020-08-05 13:25:15.080  INFO 16764 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON encoding codec LegacyJacksonJson
2020-08-05 13:25:15.081  INFO 16764 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using JSON decoding codec LegacyJacksonJson
2020-08-05 13:25:15.232  INFO 16764 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML encoding codec XStreamXml
2020-08-05 13:25:15.232  INFO 16764 --- [           main] c.n.d.provider.DiscoveryJerseyProvider   : Using XML decoding codec XStreamXml
Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.
 _ _   |_  _ _|_. ___ _ |    _ 
| | |\/|_)(_| | |_\  |_)||_|_\ 
     /               |         
                        3.1.0 
Property 'mapperLocations' was not specified or no matching resources found
Warn: Could not find @TableId in Class: com.springboot.springsecurity1.bean.Book.
2020-08-05 13:25:16.408  INFO 16764 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2020-08-05 13:25:16.491  INFO 16764 --- [           main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]
2020-08-05 13:25:16.509  WARN 16764 --- [           main] o.s.c.n.a.ArchaiusAutoConfiguration      : No spring.application.name found, defaulting to 'application'
2020-08-05 13:25:16.509  WARN 16764 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2020-08-05 13:25:16.509  INFO 16764 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2020-08-05 13:25:16.628  INFO 16764 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-05 13:25:19.268  INFO 16764 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2020-08-05 13:25:20.960  INFO 16764 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2020-08-05 13:25:21.040  INFO 16764 --- [           main] o.s.c.n.eureka.InstanceInfoFactory       : Setting initial instance status as: STARTING
2020-08-05 13:25:21.067  INFO 16764 --- [           main] com.netflix.discovery.DiscoveryClient    : Initializing Eureka in region us-east-1
2020-08-05 13:25:21.067  INFO 16764 --- [           main] com.netflix.discovery.DiscoveryClient    : Client configured to neither register nor query for data.
2020-08-05 13:25:21.074  INFO 16764 --- [           main] com.netflix.discovery.DiscoveryClient    : Discovery Client initialized at timestamp 1596605121072 with initial instances count: 0
2020-08-05 13:25:21.096  INFO 16764 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initializing ...
2020-08-05 13:25:21.098  WARN 16764 --- [           main] c.n.eureka.cluster.PeerEurekaNodes       : The replica size seems to be empty. Check the route 53 DNS Registry
2020-08-05 13:25:21.119  INFO 16764 --- [           main] c.n.e.registry.AbstractInstanceRegistry  : Finished initializing remote region registries. All known remote regions: []
2020-08-05 13:25:21.120  INFO 16764 --- [           main] c.n.eureka.DefaultEurekaServerContext    : Initialized
2020-08-05 13:25:21.239  INFO 16764 --- [           main] o.s.c.n.e.s.EurekaServiceRegistry        : Registering application UNKNOWN with eureka with status UP
2020-08-05 13:25:21.241  INFO 16764 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2020-08-05 13:25:21.241  INFO 16764 --- [      Thread-38] o.s.c.n.e.server.EurekaServerBootstrap   : Setting the eureka configuration..
2020-08-05 13:25:21.242  INFO 16764 --- [      Thread-38] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka data center value eureka.datacenter is not set, defaulting to default
2020-08-05 13:25:21.243  INFO 16764 --- [      Thread-38] o.s.c.n.e.server.EurekaServerBootstrap   : Eureka environment value eureka.environment is not set, defaulting to test
2020-08-05 13:25:21.263  INFO 16764 --- [      Thread-38] o.s.c.n.e.server.EurekaServerBootstrap   : isAws returned false
2020-08-05 13:25:21.263  INFO 16764 --- [      Thread-38] o.s.c.n.e.server.EurekaServerBootstrap   : Initialized server context
2020-08-05 13:25:21.264  INFO 16764 --- [      Thread-38] c.n.e.r.PeerAwareInstanceRegistryImpl    : Got 1 instances from neighboring DS node
2020-08-05 13:25:21.264  INFO 16764 --- [      Thread-38] c.n.e.r.PeerAwareInstanceRegistryImpl    : Renew threshold is: 1
2020-08-05 13:25:21.264  INFO 16764 --- [      Thread-38] c.n.e.r.PeerAwareInstanceRegistryImpl    : Changing status to UP
2020-08-05 13:25:21.271  INFO 16764 --- [           main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2020-08-05 13:25:21.278  INFO 16764 --- [      Thread-38] e.s.EurekaServerInitializerConfiguration : Started Eureka Server
2020-08-05 13:25:21.310  INFO 16764 --- [           main] s.d.s.w.s.ApiListingReferenceScanner     : Scanning for api listing references
2020-08-05 13:25:21.619  INFO 16764 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 10001 (http) with context path ''
2020-08-05 13:25:21.621  INFO 16764 --- [           main] .s.c.n.e.s.EurekaAutoServiceRegistration : Updating port to 10001
2020-08-05 13:25:23.291  INFO 16764 --- [           main] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
2020-08-05 13:25:23.293  INFO 16764 --- [           main] com.springboot.springsecurity1.App       : Started App in 18.863 seconds (JVM running for 20.982)
2020-08-05 13:25:24.050  INFO 16764 --- [)-192.168.218.1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-05 13:25:24.050  INFO 16764 --- [)-192.168.218.1] o.s.web.servlet.DispatcherServlet        : Initializing Servlet 'dispatcherServlet'
2020-08-05 13:25:24.062  INFO 16764 --- [)-192.168.218.1] o.s.web.servlet.DispatcherServlet        : Completed initialization in 11 ms
2020-08-05 13:26:21.284  INFO 16764 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@70a3e47] was not registered for synchronization because synchronization is not active
JDBC Connection [com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@ec7220f] will not be managed by Spring
==>  Preparing: SELECT book_id,book_name,picture,owner_id,current_owner_id,author,description,created_time,update_time FROM book WHERE book_id = ? 
==> Parameters: 17(Integer)
<==    Columns: book_id, book_name, picture, owner_id, current_owner_id, author, description, created_time, update_time
<==        Row: 17, 乖,摸摸头2.0, /0000000, 1, 10000, 大冰, 大冰畅·销450万册作品升级版!重写续写增写原书内容,增加10篇全新文章!随书附赠书中主人公们对话声音、18首原创民谣歌曲!乖,摸摸头,来,不要走散,抱团取暖。 , 2019-11-13 21:39:41, 2019-11-13 21:39:41
<==      Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@70a3e47]
Book{bookId=17, bookName='乖,摸摸头2.0', picture='/0000000', ownerId=1, currentOwnerId=10000, author='大冰', description='大冰畅·销450万册作品升级版!重写续写增写原书内容,增加10篇全新文章!随书附赠书中主人公们对话声音、18首原创民谣歌曲!乖,摸摸头,来,不要走散,抱团取暖。 ', createdTime=Thu Nov 14 05:39:41 CST 2019, updateTime=Thu Nov 14 05:39:41 CST 2019}
2020-08-05 13:27:21.267  INFO 16764 --- [a-EvictionTimer] c.n.e.registry.AbstractInstanceRegistry  : Running the evict task with compensationTime 0ms

二、Eureka

在启动类上加上@EnableEurekaServer,启动一个服务注册中心

yml文件中添加

server:
  port: 10001
eureka:
  client:
    register-with-eureka: false #是否向服务中心注册自己
    fetch-registry: false #是否检索服务
    serviceUrl: #指定服务中心的位置
      defaultZone: http://localhost:10001/eureka

就可以访问啦

 

仔细看,没有实例

创建好之后的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.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.eureka</groupId>
    <artifactId>provider</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>provider</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.SR6</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

但是启动报错了

 把pom中dependencyManagement换成下面的就可以解决

 <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

启动类

package com.eureka.provider;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.web.bind.annotation.RestController;

/**
 * Eureka客户端
 */
@EnableEurekaClient
@SpringBootApplication
public class ProviderApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }

}

Controller

package com.eureka.provider.Controller;

import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/provider")
public class testController {

    /**
     * 假如这个客户端要提供一个getUser的方法
     * @return
     */
    @GetMapping(value = "/getUser")
    @ResponseBody
    public Map<String,Object> getUser(@RequestParam Integer id){
        Map<String,Object> data = new HashMap<>();
        data.put("id",id);
        data.put("userName","admin");
        data.put("from","provider-A");
        return data;
    }


}

yml


eureka:
  client:
    serviceUrl: #注册中心的注册地址
      defaultZone: http://127.0.0.1:10001/eureka/  #这是那个项目
server:
  port: 8082  #服务端口号  这里的
spring:
  application:
    name: service-provider #服务名称--调用的时候根据名称来调用该服务的方法

再localhost:10001去访问

但是用这个http://localhost:10001/provider/getUser

访问是404

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值