上文(spring cloud学习笔记之Feign自定义(Java配置):https://mp.csdn.net/postedit/89818667)讲解了自定义Feign。但是在某些场景下,前文自定义Feign的方式满足不了需求,此时可使用Feign Builder API手动创建Feign。
本文围绕以下场景,为大家讲解如何手动创建Feign。
1、创建项目microservice-provider-user-feignBuilder,导入相关依赖,pom.xml
org.springframework.boot
spring-boot-starter-data-jpa
org.springframework.boot
spring-boot-starter-security
org.springframework.boot
spring-boot-starter-web
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.cloud
spring-cloud-starter-netflix-ribbon
org.springframework.cloud
spring-cloud-starter-openfeign
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
org.springframework.security
spring-security-test
test
2、新建security包,创建SecurityUser类:
package com.vainglory.stySpringCloud.security;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
public class SecurityUser implements UserDetails {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String username;
private String password;
private String role;
public SecurityUser() {
}
public SecurityUser(String username, String password, String role) {
this.username = username;
this.password = password;
this.role = role;
}
@Override
public Collection extends GrantedAuthority> getAuthorities() {
Collection authorities = new ArrayList();
SimpleGrantedAuthority authority = new SimpleGrantedAuthority(this.role);
authorities.add(authority);
return authorities;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return username;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
//省略getter和setter方法
}
3、创建CustomUserDetailsService类
package com.vainglory.stySpringCloud.security;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
@Component
public class CustomUserDetailsService implements UserDetailsService {
/**
* 模拟两个账户
* ① 账号是user,密码是password1,角色是user-role
* ② 账号时候admin,密码是password1,角色是admin-role
* @param username
* 用户名
* @return
*
* @throws UsernameNotFoundException
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
if ("user".equals(username)) {
return new SecurityUser("user", "password1", "user-role");
} else if ("admin".equals(username)) {
return new SecurityUser("admin", "password2", "admin-role");
} else {
return null;
}
}
}
4、创建Spring Security配置类
package com.vainglory.stySpringCloud.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsService userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
// 所有的请求,都需要经过HTTP basic认证
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Bean
public PasswordEncoder passwordEncoder() {
// 明文编码器。这个一个不做任何操作的密码编码器,是Spring提供给我们做明文测试的
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(this.userDetailsService).passwordEncoder(this.passwordEncoder());
}
}
5、UserRepository类
package com.vainglory.stySpringCloud.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.vainglory.stySpringCloud.entity.User;
@Repository
public interface UserRepository extends JpaRepository {
}
6、Controller
package com.vainglory.stySpringCloud.controller;
import java.util.Collection;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.vainglory.stySpringCloud.entity.User;
import com.vainglory.stySpringCloud.repository.UserRepository;
@RestController
public class UserController {
@Autowired
private UserRepository userRepository;
private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);
@GetMapping("/{id}")
public Optional findById(@PathVariable Long id) {
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
UserDetails user = (UserDetails) principal;
Collection extends GrantedAuthority> collection = user.getAuthorities();
for (GrantedAuthority c : collection) {
// 打印当前登录用户的信息
UserController.LOGGER.info("当前用户是{},角色是{}", user.getUsername(), c.getAuthority());
}
} else {
// do other things
}
Optional findOne = this.userRepository.findById(id);
return findOne;
}
}
7、Entity Bean
package com.vainglory.stySpringCloud.entity;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column
private String username;
@Column
private String name;
@Column
private Integer age;
@Column
private BigDecimal balance;
//省略getter和setter方法
}
8、启动类
package com.vainglory.stySpringCloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class MicroserviceConsumerMovieFrignBuilderApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceConsumerMovieFrignBuilderApplication.class, args);
}
}
9、properties配置文件
server.port=8888
spring.datasource.url=jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=sx96411
#jpa
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
#Eureka
spring.application.name=microservice-provider-user
eureka.client.serviceUrl.defaultZone=http://suxing:suxing123@localhost:8000/eureka/
eureka.instance.prefer-ip-address=true
#eureka.instance.instance-id=${spring.application.name}:${spring.application.instance_id:${server.port}}
10、测试User微服务
> 启动 microservice-discovery-eureka
> 启动 microservice-provider-user-feignBuilder
> 访问 http://localhost:8000/1,弹出登录对话框:
> 使用 user/password1 登录,可在控制台看到如下日志
> 使用 admin/password2 登录,可在控制台看到如下日志
1、pom.xml:
org.springframework.cloud
spring-cloud-starter-netflix-eureka-server
org.springframework.cloud
spring-cloud-starter-netflix-ribbon
org.springframework.cloud
spring-cloud-starter-openfeign
2、properties配置文件
server.port=8889
spring.datasource.url=jdbc:mysql://localhost:3306/springcloud?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=sx96411
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
#jpa
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
#eureka
spring.application.name=microservice-consumer-movie
eureka.client.serviceUrl.defaultZone=http://suxing:suxing123@localhost:8000/eureka/
eureka.instance.prefer-ip-address=true
#Ribbon
#ribbon.eureka.enabled=false
#ribbon.eager-load.enabled=true
#ribbon.eager-load.clients=client1
3、Bean
package com.vainglory.stySpringCloud.entity;
import java.math.BigDecimal;
public class User {
private Long id;
private String username;
private String name;
private Integer age;
private BigDecimal balance;
//省略getter和setter方法
}
4、UserFeignClient类
package com.vainglory.stySpringCloud.feign;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import com.vainglory.stySpringCloud.entity.User;
public interface UserFeignClient {
@GetMapping(value = "/{id}")
User findById(@PathVariable("id") Long id);
}
5、Controller
package com.vainglory.stySpringCloud.controller;
import org.springframework.cloud.openfeign.FeignClientsConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import com.vainglory.stySpringCloud.entity.User;
import com.vainglory.stySpringCloud.feign.UserFeignClient;
import feign.Client;
import feign.Contract;
import feign.Feign;
import feign.auth.BasicAuthRequestInterceptor;
import feign.codec.Decoder;
import feign.codec.Encoder;
@Import(FeignClientsConfiguration.class) // Spring Cloud为Feign默认提供的配置类
@RestController
public class MovieController {
private UserFeignClient userUserFeignClient;
private UserFeignClient adminUserFeignClient;
public MovieController(Decoder decoder, Encoder encoder, Client client, Contract contract) {
this.userUserFeignClient = Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract)
.requestInterceptor(new BasicAuthRequestInterceptor("user", "password1"))
.target(UserFeignClient.class, "http://microservice-provider-user/");
this.adminUserFeignClient = Feign.builder().client(client).encoder(encoder).decoder(decoder).contract(contract)
.requestInterceptor(new BasicAuthRequestInterceptor("admin", "password2"))
.target(UserFeignClient.class, "http://microservice-provider-user/");
}
@GetMapping("/user-user/{id}")
public User findByIdUser(@PathVariable Long id) {
return this.userUserFeignClient.findById(id);
}
@GetMapping("/user-admin/{id}")
public User findByIdAdmin(@PathVariable Long id) {
return this.adminUserFeignClient.findById(id);
}
}
6、启动类
package com.vainglory.stySpringCloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@EnableDiscoveryClient
@SpringBootApplication
public class MicroserviceConsumerMovieFeignBuilderApplication {
public static void main(String[] args) {
SpringApplication.run(MicroserviceConsumerMovieFeignBuilderApplication.class, args);
}
}
7、测试
> 启动 microservice-discovery-eureka
> 启动 microservice-provider-user-feignBuilder
> 启动 microservice-consumer-movie-feignBuilder
> 访问 http://localhost:8010/user-user/1,可正常获取结果,并且在用户微服务控制台打印如下日志
> 访问 http://localhost:8010/user-admin/1,可正常获取结果,并且在用户微服务控制台打印如下日志
参考博文:https://www.cnblogs.com/jinjiyese153/p/8664370.html