在Spring Cloud项目中使用Feign,您可以按照以下步骤进行设置和使用:
- 添加依赖:首先,您需要在项目的构建配置文件(如Maven的pom.xml)中添加Feign依赖项。确保您使用的是与您的Spring Cloud版本兼容的Feign版本。例如,对于Spring Cloud 2020.0.x版本,可以使用以下依赖项:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- 启用Feign:在您的Spring Boot应用程序的主类上添加
@EnableFeignClients
注解,以启用Feign客户端。该注解将自动扫描并创建Feign客户端的实例。
import org.springframework.cloud.openfeign.EnableFeignClients;
@EnableFeignClients
@SpringBootApplication
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 创建Feign客户端接口:定义一个Feign客户端接口,该接口将映射到您要调用的远程服务的API。您可以使用Spring MVC的注解来描述接口的方法和参数。
@FeignClient(value = "checkcode",fallbackFactory = CheckCodeClientFactory.class)
@RequestMapping("/checkcode") // 指定远程服务的名称
public interface CheckCodeClient {
@PostMapping(value = "/verify") // 定义要调用的远程服务的API路径
public Boolean verify(@RequestParam("key") String key, @RequestParam("code") String code);
}
- 使用Feign客户端:在您的业务逻辑中,通过注入Feign客户端接口来使用它。
@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {
@Autowired
XcUserMapper xcUserMapper;
@Autowired
PasswordEncoder passwordEncoder;
@Autowired
CheckCodeClient checkCodeClient;
@Override
public XcUserExt execute(AuthParamsDto authParamsDto) {
//账号
String username = authParamsDto.getUsername();
//输入的验证码
String checkcode = authParamsDto.getCheckcode();
//验证码对应的key
String checkcodekey = authParamsDto.getCheckcodekey();
if(StringUtils.isEmpty(checkcode) || StringUtils.isEmpty(checkcodekey)){
throw new RuntimeException("请输入的验证码");
}
//远程调用验证码服务接口去校验验证码
Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
if(verify == null||!verify){
throw new RuntimeException("验证码输入错误");
}
//账号是否存在
//根据username账号查询数据库
XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));
//查询到用户不存在,要返回null即可,spring security框架抛出异常用户不存在
if(xcUser==null){
throw new RuntimeException("账号不存在");
}
//验证密码是否正确
//如果查到了用户拿到正确的密码
String passwordDb = xcUser.getPassword();
//拿 到用户输入的密码
String passwordForm = authParamsDto.getPassword();
//校验密码
boolean matches = passwordEncoder.matches(passwordForm, passwordDb);
if(!matches){
throw new RuntimeException("账号或密码错误");
}
XcUserExt xcUserExt = new XcUserExt();
BeanUtils.copyProperties(xcUser,xcUserExt);
return xcUserExt;
}
}
以上就是使用Feign的基本步骤。您可以在Feign客户端接口中定义多个方法,每个方法对应不同的远程服务API。Feign会根据接口定义自动生成代理对象,简化了与远程服务的交互。