赞
踩
说明:本文章是自己在学习spring boot中使用Nacos服务注册和发现时记录的当做笔记了,有什么不对的欢迎指正。
当你来搜索spring boot中使用nacos的时候就应该知道nacos是什么了,这里就不多废话了,直接看下面的使用吧
步骤:
成功的页面如下:
进入里面的的网页可以看到如下界面:
<!-- 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>
server:
port: 8081
ip: localhost
spring:
application:
name: userserver
nacos:
discovery:
# 设置自动注册,默认是false
auto-register: true
# nacos server的ip和端口
server-addr: localhost:8848
启动项目后可以在nacos server看的如下界面,已经注册到了服务中心
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注解的,用了反而注册不上
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;
}
需求:写两个服务,一个user服务,一个user_log服务,在user服务获取用户信息时我们需要调用user_log服务来获取对应用户的日志列表。
数据库数据准备
表1:user
表2:user_log
<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>
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
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); } }
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(); } }
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; }
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; } }
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类
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; }
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; }
<?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>
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); } }
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
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); }
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); } }
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; }
nacos服务中心
postman 发起请求测试
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。