系列文章目录
文章目录
前言
本文我们要讲述:
OpenFeign
在下攸攸太上,今天依旧帅气。
一、OpenFeign介绍
1. Feign框架介绍
Feign是一个用于处理HTTP请求的框架,集成了负载均衡、熔断机制和HTTP请求管理等功能,旨在进行微服务通信。
负载均衡:帮助降低服务器的压力,确保各个服务器承担的压力相对均衡。
熔断机制:用于处理微服务之间的通信,防止由于某一服务宕机导致长时间等待响应的情况。
HTTP请求管理:用于实现微服务间的HTTP通信。
2. OpenFeign框架
OpenFeign是SpringCloud下的一个框架,用于微服务通信,采用RESTful风格进行服务间通信。
OpenFeign基于Feign框架,但在Spring环境下进行了二次升级,天然支持Spring的思想和注解,使得开发变得更加简单。
3. Feign与OpenFeign的区别
Feign对HTTP进行了封装,实现微服务通信;而OpenFeign是在Spring环境下对Feign进行的二次升级,使得框架更加简单、更贴近Spring,减少了开发者在使用时的障碍。
二、代码实现
此项目在SpringSession项目基础上编写,此网盘链接内有已完成的项目
通过网盘分享的文件:SpringSession——OpenFeign.zip
链接: https://pan.baidu.com/s/1-XC15nXgLlSZiumph1aqFw?pwd=u8y1 提取码: u8y1
1. 开启nacos和redis
docker start nacos
docker start redis-6379
2. 创建Score实体类(两个项目共同改动)
package com.jjy.entry;
import lombok.Data;
@Data
public class Score {
private String name;
private Double score;
}
3. 创建UserDto实体类(两个项目共同改动)
import lombok.Data;
import java.util.List;
@Data
public class UserDto {
private String id;
private String name;
private String password;
private List<Score> scoreList;
}
4. 添加IUserService接口
4.1 demo-session-01改动
package com.jjy.service;
import com.jjy.entry.UserDto;
public interface IUserService {
public UserDto info();
}
4.2 demo-session-02改动
package com.jjy.service;
import com.jjy.entry.Score;
import java.util.List;
public interface IScoreService {
public List<Score> info();
}
5. 添加UserServiceImpl接口实现类(两个项目共分别改动)
5.1 demo-session-01改动
package com.jjy.service.impl;
import com.jjy.entry.UserDto;
import com.jjy.service.IUserService;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements IUserService {
@Override
public UserDto info() {
return new UserDto();
}
}
5.2 demo-session-02改动
package com.jjy.service.impl;
import com.jjy.entry.Score;
import com.jjy.service.IScoreService;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
@Service
public class ScoreServiceImpl implements IScoreService {
@Override
public List<Score> info() {
List<Score> result = new ArrayList<>();
for (int i=0;i<3;i++){
Score score=new Score();
score.setName("name"+i);
score.setScore(Math.random()*10);
result.add(score);
}
return result;
}
}
6. 创建ResultCode枚举类(两个项目共同改动)
package com.jjy.util;
public enum ResultCode {
SUCCESS(0, "请求成功"),
ERROR(1, "请求失败"),
;
private int code;
private String message;
ResultCode(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public String getMessage() {
return message;
}
}
7. 创建Result工具类(两个项目共同改动)
package com.jjy.util;
import lombok.Data;
import java.util.HashMap;
import java.util.Map;
@Data
public class Result {
private Integer code;
private String message;
private Map<String, Object> map = new HashMap<>();
private Result() {
}
public static Result ok() {
Result r = new Result();
r.setCode(ResultCode.SUCCESS.getCode());
r.setMessage(ResultCode.SUCCESS.getMessage());
return r;
}
public static Result error() {
Result r = new Result();
r.setCode(ResultCode.ERROR.getCode());
r.setMessage(ResultCode.ERROR.getMessage());
return r;
}
public Result put(String key, Object value) {
map.put(key, value);
return this;
}
public Object get(String key) {
return map.get(key);
}
}
8. 更新UserController/ScoreController类
8.1 demo-session-01改动
package com.jjy.controller;
import com.jjy.entry.UserDto;
import com.jjy.service.IUserService;
import com.jjy.util.Result;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/user")
@Setter
public class UserController {
@Autowired
private IUserService userService;
@GetMapping
public Result info(){
UserDto userDto=userService.info();
return Result.ok().put("data",userDto);
}
}
8.2 demo-session-02改动
删除UserController类
package com.jjy.controller;
import com.jjy.entry.Score;
import com.jjy.service.IScoreService;
import com.jjy.util.Result;
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.RestController;
import java.util.List;
@RestController
@RequestMapping("/score")
public class ScoreController {
@Autowired
private IScoreService scoreService;
@GetMapping("/info")
public Result info(){
List<Score> list=scoreService.info();
return Result.ok().put("list",list);
}
}
9. 更改配置文件
9.1 demo-session-01改动
spring.application.name=openfeignDemo1
9.2 demo-session-02改动
spring.application.name=openfeignDemo2
10. 运行项目,访问链接
http://127.0.0.1:100/user
http://127.0.0.1:200/score/info
三、实现http请求管理
1. 添加openfeign依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2. 创建ScoreFeign接口(demo-session-01改动)
package com.jjy.service;
import com.jjy.util.Result;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
@FeignClient("openfeignDemo2")
public interface ScoreFeign {
@GetMapping("/score/info")
public Result info();
}
3. 更新UserServiceImpl文件(demo-session-01改动)
scoreFeign会爆红,不用管,下一步就不会了,OpenFeign会自动生成ScoreFeign的代理类
package com.jjy.service.impl;
import com.jjy.entry.Score;
import com.jjy.entry.UserDto;
import com.jjy.service.IUserService;
import com.jjy.service.ScoreFeign;
import com.jjy.util.Result;
import com.jjy.util.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private ScoreFeign scoreFeign;
@Override
public UserDto info() {
UserDto userDto=new UserDto();
userDto.setId("10");
userDto.setName("zhangsan");
userDto.setPassword("123456");
Result result=scoreFeign.info();
if(result.getCode() == ResultCode.SUCCESS.getCode()){
userDto.setScoreList((List<Score>) result.get("list"));
}
return userDto;
}
}
4. 更新SpringBootMain启动类(demo-session-01改动)
@EnableFeignClients //开始OPenFeign
5. 启动项目
demo-session-01项目:查看用户数据的同时,也可以获得demo-session-02的数据
demo-session-02项目不变
四、添加请求头
1. 更新UserController类(demo-session-01改动)
package com.jjy.controller;
import com.jjy.entry.UserDto;
import com.jjy.service.IUserService;
import com.jjy.util.Result;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
@RestController
@RequestMapping("/user")
@Setter
public class UserController {
@Autowired
private IUserService userService;
@GetMapping
public Result info(HttpServletRequest request){ // 添加参数
// 更新部分
String test = request.getHeader("test");
System.out.println("User项目header:"+test);
// 更新部分
UserDto userDto=userService.info();
return Result.ok().put("data",userDto);
}
}
2. 更新ScoreController类(demo-session-02改动)
package com.jjy.controller;
import com.jjy.entry.Score;
import com.jjy.service.IScoreService;
import com.jjy.util.Result;
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.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping("/score")
public class ScoreController {
@Autowired
private IScoreService scoreService;
@GetMapping("/info")
public Result info(HttpServletRequest request){ // 添加参数
// 更新部分
String test = request.getHeader("test");
System.out.println("Score项目header:"+test);
// 更新部分
List<Score> list=scoreService.info();
return Result.ok().put("list",list);
}
}
3. 启动项目、启动postman发送请求
按照如下步骤发送请求
可以看到User项目的header接收到了信息,Score项目header没接收到
4. 创建RequestHeaderInterceptor拦截器(demo-session-01改动)
package com.jjy.interceptor;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Configuration
public class RequestHeaderInterceptor implements RequestInterceptor {
@Override
public void apply(RequestTemplate template) {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
if (requestAttributes == null) {
return;
}
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
String test = request.getHeader("test");
template.header("test", test);
}
}
5. 重新启动demo-session-01项目、postman发送请求
四、参数传递
1. 更新ScoreFeign接口(demo-session-01改动)
添加如下两个方法:
@GetMapping("/score/{id}")
Result id(@PathVariable String id);
@PostMapping("/score/add")
Result add(@RequestBody UserDto user);
2. 更新IUserService接口(demo-session-01改动)
添加如下两个方法:
UserDto add(UserDto user);
UserDto id(String id);
3. 更新UserServiceImpl实现类(demo-session-01改动)
@Override
public UserDto add(UserDto user) {
UserDto userDto = new UserDto();
Result result = scoreFeign.add(user);
if(result.getCode() == ResultCode.SUCCESS.getCode()){
UserDto resultUser = JSON.parseObject(JSON.toJSONString(result.get("data")),UserDto.class);
BeanUtils.copyProperties(resultUser, userDto);
}
return userDto;
}
@Override
public UserDto id(String id) {
UserDto userDto = new UserDto();
Result result = scoreFeign.id(id);
if(result.getCode() == ResultCode.SUCCESS.getCode()){
userDto.setId((String) result.get("id"));
}
return userDto;
}
4. 更新UserController类(demo-session-01改动)
添加如下两个方法:
@GetMapping("/{id}")
public Result id(@PathVariable String id) { //url传值
UserDto userDto = userService.id(id);
return Result.ok().put("data", userDto);
}
@PostMapping("/add")
public Result add(@RequestBody UserDto user) { //对象传值
return Result.ok().put("userDto", user);
}
5. 更新ScoreController类(demo-session-02改动)
添加如下两个方法:
@GetMapping("/{id}")
public Result id(@PathVariable String id) {
return Result.ok().put("id", id);
}
@PostMapping("/add")
public Result add(@RequestBody UserDto user) {
return Result.ok().put("userDto", user);
}
6. 启动项目、postman发送请求
测试ID方法:
测试ADD方法:
总结
本文讲述了:
OpenFeign:能够处理Http请求
通过网盘分享的文件:SpringSession——OpenFeign.zip
链接: https://pan.baidu.com/s/1-XC15nXgLlSZiumph1aqFw?pwd=u8y1 提取码: u8y1
在下攸攸太上,正在留长发。