1、注解
| |
| <dependency> |
| <groupId>com.alibaba.cloud</groupId> |
| <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> |
| </dependency> |
| |
| |
| <dependency> |
| <groupId>io.github.openfeign</groupId> |
| <artifactId>feign-okhttp</artifactId> |
| </dependency> |
下面这两个依赖写在api的包下,其中loadbalancer写完了之后,它会自动配置 Spring Cloud LoadBalancer 的客户端负载均衡器,使得应用程序可以无缝地使用负载均衡功能。
| |
| <dependency> |
| <groupId>org.springframework.cloud</groupId> |
| <artifactId>spring-cloud-starter-openfeign</artifactId> |
| </dependency> |
| |
| <dependency> |
| <groupId>org.springframework.cloud</groupId> |
| <artifactId>spring-cloud-starter-loadbalancer</artifactId> |
| </dependency> |
2、com.twinkle.api.config
该文件夹下写OpenFeign配置类
| import feign.Logger; |
| import org.springframework.context.annotation.Bean; |
| |
| public class DefaultFeignConfig { |
| @Bean |
| public Logger.Level feignLogLevel() { |
| return Logger.Level.BASIC; |
| } |
| } |
同时在启动类上注明@EnableFeignClients(basePackages = "com.twinkle.api.clients", defaultConfiguration = DefaultFeignConfig.class)
(启用OpenFeignClients,写明clients包所在目录,写明OpenFeign的配置类)
3、编写com.twinkle.api.clients
| import org.springframework.cloud.openfeign.FeignClient; |
| import org.springframework.web.bind.annotation.DeleteMapping; |
| import org.springframework.web.bind.annotation.RequestParam; |
| |
| import java.util.Collection; |
| |
| @FeignClient("cart-service") |
| public interface CartClient { |
| @DeleteMapping("/carts") |
| void deleteCartItemByIds(@RequestParam("ids") Collection<Long> ids); |
| } |
4、application.yaml
每个微服务下的application.yaml
| server: |
| port: 8082 |
| spring: |
| application: |
| name: twinkle-service |
| profiles: |
| active: dev |
| datasource: |
| url: jdbc:mysql://${hm.db.host}:3306/twinkle?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai |
| driver-class-name: com.mysql.cj.jdbc.Driver |
| username: root |
| password: ${hm.db.pw} |
| cloud: |
| nacos: |
| server-addr: 127.0.0.1:8848 |
| feign: |
| okhttp: |
| enabled: true |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步