说明:本文章是自己在学习spring boot中使用Nacos服务注册和发现时记录的当做笔记了,有什么不对的欢迎指正。
当你来搜索spring boot中使用nacos的时候就应该知道nacos是什么了,这里就不多废话了,直接看下面的使用吧
1、服务注册:
步骤:
1、去官网安装nacos并且启动nacos service.
成功的页面如下:
进入里面的的网页可以看到如下界面:
2、建立spring boot项目引入相关依赖jar包
<!-- spring boot 核心依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- nacos注册依赖-->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.12</version>
</dependency>
</dependencies>
3、使项目启动自动注册到服务中心
1、通过配置实现(更推荐,下面的案例也是写yml文件来配置)
server:
port: 8081
ip: localhost
spring:
application:
name: userserver
nacos:
discovery:
# 设置自动注册,默认是false
auto-register: true
# nacos server的ip和端口
server-addr: localhost:8848
启动项目后可以在nacos server看的如下界面,已经注册到了服务中心
2、写配置类(依然需要在配置文件中设置nacos server的ip和端口)
package com.example.config;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
* Created by IntelliJ IDEA.
*
* @Author : wlh
* @create 2023/1/18 18:15
*/
@Configuration
public class NacosRegisterConfig {
// 服务名称
@Value("${spring.application.name}")
private String applicationName;
// 服务的端口号
@Value("${server.port}")
private Integer port;
// 服务ip地址
@Value("${server.ip}")
private String ip;
@NacosInjected
private NamingService namingService;
// @PostConstruct 在依赖注入完成时执行注解的方法
@PostConstruct
public void register() throws NacosException {
namingService.registerInstance(applicationName,ip,port);
}
}
然后在启动类上写上注解@EnableNacosDiscovery。执行后一样的可以在nacos server里面看到注册的服务。
但是需要注意的是:使用配置文件的形式在启动类上是不需要@EnableNacosDiscovery注解的,用了反而注册不上
2、服务发现和调用:
1、获取服务:
使用NamingService对象的selectOneHealthyInstance(“服务名称”);获取一个服务,参数是服务名称。这个方法的作用是根据参数获取对应的服务,如果有多个(集群时)会自己去调用一个(要不是随机的,要不是轮询调度)。
2、远程调用:
RestTemplate对象的方法能够实现远程调用
getForObject — optionsForAllow 分为一组,这类方法是常规的 Rest API(GET、POST、DELETE 等)方法调用;
exchange:接收一个 RequestEntity 参数,可以自己设置 HTTP method,URL,headers 和 body,返回 ResponseEntity;
execute:通过 callback 接口,可以对请求和返回做更加全面的自定义控制。
如下:
public UserDto queryById(Integer id) throws NacosException {
User user = userMapper.selectById(id);
UserDto userDto = new UserDto();
userDto.setId(user.getId());
userDto.setName(user.getName());
userDto.setMoney(user.getMoney());
// 获取服务
Instance logserver = namingService.selectOneHealthyInstance("logserver");
String url = String.format("http://%s:%d/userLog/queryByUserId/"+id,logserver.getIp(),logserver.getPort());
// 通过restTemplate对象进行跨模块请求数据
List list = restTemplate.getForObject(url, List.class);
userDto.setUserLogs(list);
return userDto;
}
3、完整案例
需求:写两个服务,一个user服务,一个user_log服务,在user服务获取用户信息时我们需要调用user_log服务来获取对应用户的日志列表。
数据库数据准备
表1:user
表2:user_log
user服务:
引入依赖:
<groupId>ikiku.space</groupId>
<artifactId>user-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>user_server</name>
<description>user_server</description>
<?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.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ikiku.space</groupId>
<artifactId>user-server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>user_server</name>
<description>user_server</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<!-- spring boot 核心依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mysql驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- mybatis代码生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.2</version>
</dependency>
<!-- 模板-->
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- swager注解依赖-->
<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>
<!-- nacos注册依赖-->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
yml文件
server:
# 端口
port: 8081
# ip
ip: localhost
spring:
application:
name: userserver #服务的名称
# 连接数据库的数据源
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/db2?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
nacos:
discovery:
# 自动注册
auto-register: true
# nacos服务地址
server-addr: localhost:8848
controller层:
package com.example.controller;
import com.alibaba.nacos.api.exception.NacosException;
import com.example.dto.UserDto;
import com.example.service.UserLogService;
import com.example.service.UserService;
import jdk.nashorn.internal.ir.ReturnNode;
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;
/**
* <p>
* 前端控制器
* </p>
*
* @author wlh
* @since 2023-01-18
*/
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/query/{id}")
public UserDto queryById(@PathVariable("id") Integer id) throws NacosException {
return userService.queryById(id);
}
}
config层
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
/**
* Created by IntelliJ IDEA.
*
* @Author : wlh
* @create 2023/1/18 17:20
*/
@Configuration
public class NacosConfig {
// 注入RestTemplate对象
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
service层
package com.example.service;
import com.alibaba.nacos.api.exception.NacosException;
import com.example.dto.UserDto;
import com.example.entity.User;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 服务类
* </p>
*
* @author wlh
* @since 2023-01-18
*/
public interface UserService extends IService<User> {
// 根据id获取用户信息和日志列表
UserDto queryById(Integer id) throws NacosException;
}
service实现类
package com.example.service.impl;
import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.example.dto.UserDto;
import com.example.entity.User;
import com.example.entity.UserLog;
import com.example.mapper.UserMapper;
import com.example.service.UserLogService;
import com.example.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author wlh
* @since 2023-01-18
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
@Resource
private UserMapper userMapper;
@Autowired
private RestTemplate restTemplate;
@NacosInjected
private NamingService namingService;
@Override
public UserDto queryById(Integer id) throws NacosException {
User user = userMapper.selectById(id);
UserDto userDto = new UserDto();
userDto.setId(user.getId());
userDto.setName(user.getName());
userDto.setMoney(user.getMoney());
// 获取服务
Instance logserver = namingService.selectOneHealthyInstance("logserver");
String url = String.format("http://%s:%d/userLog/queryByUserId/"+id,logserver.getIp(),logserver.getPort());
// 通过restTemplate对象进行夸模块请求数据
List list = restTemplate.getForObject(url, List.class);
userDto.setUserLogs(list);
return userDto;
}
}
mapper层
package com.example.mapper;
import com.example.entity.User;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wlh
* @since 2023-01-18
*/
public interface UserMapper extends BaseMapper<User> {
}
实体类
user类
package com.example.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.math.BigDecimal;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author wlh
* @since 2023-01-18
*/
@Getter
@Setter
@Accessors(chain = true)
@TableName("user")
@ApiModel(value = "User对象", description = "")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键")
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@ApiModelProperty("姓名")
@TableField("name")
private String name;
@ApiModelProperty("账户余额")
@TableField("money")
private BigDecimal money;
}
UserLog类文章来源:https://www.toymoban.com/news/detail-647600.html
package com.example.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author wlh
* @since 2023-01-18
*/
@Getter
@Setter
@Accessors(chain = true)
@TableName("user_log")
@ApiModel(value = "UserLog对象", description = "")
public class UserLog implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("message")
private String message;
@TableField("time")
private LocalDateTime time;
@TableField("user_id")
private Integer userId;
}
dto用于定义数据传输模板
package com.example.dto;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.example.entity.UserLog;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.List;
/**
* Created by IntelliJ IDEA.
*
* @Author : wlh
* @create 2023/1/18 17:12
*/
@Data
public class UserDto implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键")
private Integer id;
@ApiModelProperty("姓名")
private String name;
@ApiModelProperty("账户余额")
private BigDecimal money;
@ApiModelProperty("日志列表")
private List<UserLog> userLogs;
}
user_log服务
引入依赖
<?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.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>ikiku.space</groupId>
<artifactId>log_server</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>log_server</name>
<description>log_server</description>
<properties>
<java.version>8</java.version>
</properties>
<dependencies>
<!-- spring boot 核心依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- spring boot测试依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!-- mysql驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis-plus依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.2</version>
</dependency>
<!-- mybatis代码生成器依赖-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.2</version>
</dependency>
<!-- freemarker模板-->
<!-- https://mvnrepository.com/artifact/org.freemarker/freemarker -->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.31</version>
</dependency>
<!-- lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- swagger注解依赖-->
<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>
<!-- nacos注册依赖-->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-discovery-spring-boot-starter</artifactId>
<version>0.2.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
controller层
package com.example.controller;
import com.example.entity.UserLog;
import com.example.service.UserLogService;
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 java.util.List;
/**
* <p>
* 前端控制器
* </p>
*
* @author wlh
* @since 2023-01-18
*/
@RestController
@RequestMapping("/userLog")
public class UserLogController {
@Autowired
private UserLogService userLogService;
@GetMapping("/queryByUserId/{id}")
public List<UserLog> getLog(@PathVariable("id") Integer id){
return userLogService.queryById(id);
}
}
config层暂时不需要,如果需要跨模块访问其他的模块时,在写的和user服务里面的一样即可
yml配置
server:
port: 8082
ip: localhost
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123456
url: jdbc:mysql://localhost:3306/db2?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false
application:
name: logserver
nacos:
discovery:
auto-register: true
server-addr: localhost:8848
service层
package com.example.service;
import com.example.entity.UserLog;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
/**
* <p>
* 服务类
* </p>
*
* @author wlh
* @since 2023-01-18
*/
public interface UserLogService extends IService<UserLog> {
List<UserLog> queryById(Integer id);
}
service实现类层
package com.example.service.impl;
import com.example.entity.UserLog;
import com.example.mapper.UserLogMapper;
import com.example.service.UserLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
/**
* <p>
* 服务实现类
* </p>
*
* @author wlh
* @since 2023-01-18
*/
@Service
public class UserLogServiceImpl extends ServiceImpl<UserLogMapper, UserLog> implements UserLogService {
@Resource
private UserLogMapper userLogMapper;
@Override
public List<UserLog> queryById(Integer id) {
return userLogMapper.queryByUserId(id);
}
}
mapper层
package com.example.mapper;
import com.example.entity.UserLog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* <p>
* Mapper 接口
* </p>
*
* @author wlh
* @since 2023-01-18
*/
public interface UserLogMapper extends BaseMapper<UserLog> {
@Select("select * from user_log where user_id = #{id}")
List<UserLog> queryByUserId(@Param("id") Integer id);
}
实体类层
package com.example.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.time.LocalDateTime;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
/**
* <p>
*
* </p>
*
* @author wlh
* @since 2023-01-18
*/
@Getter
@Setter
@Accessors(chain = true)
@TableName("user_log")
@ApiModel(value = "UserLog对象", description = "")
public class UserLog implements Serializable {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
@TableField("message")
private String message;
@TableField("time")
private LocalDateTime time;
@TableField("user_id")
private Integer userId;
}
postman测试验证正确性
nacos服务中心
postman 发起请求测试
文章来源地址https://www.toymoban.com/news/detail-647600.html
到了这里,关于Nacos在spring boot的使用的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!