zhuxs / spring-shiro-spark Goto Github PK
View Code? Open in Web Editor NEWSpring-Shiro-Spark是Spring-Boot Hibernate Spark Spark-SQL Shiro iView VueJs... ...的集成尝试
License: Apache License 2.0
Spring-Shiro-Spark是Spring-Boot Hibernate Spark Spark-SQL Shiro iView VueJs... ...的集成尝试
License: Apache License 2.0
前端代码越来越复杂
前后端高度耦合
分工问题
后端
前端
标准
Subject subject = SecurityUtils.getSubject();
subject.login(token);
@Bean(name = "securityManager")
public DefaultWebSecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//设置Realm
securityManager.setRealm(shiroRealm());
//设置session管理器
securityManager.setSessionManager(sessionManager());
return securityManager;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//赋予角色和权限
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
//用户认证
}
filterChainDefinitionManager.put("/userInfo","authc"); //需要登录
filterChainDefinitionManager.put("/jobs/**","perms[JOB:CREATE]"); //需要[JOB:CREATE]权限
filterChainDefinitionManager.put("/admin/**","roles[Admin]"); //需要Admin角色
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//获取当前用户
UserDto user = (UserDto) SecurityUtils.getSubject().getSession().getAttribute("user");
//把principals放session中,key=userId value=principals
SecurityUtils.getSubject().getSession().setAttribute(String.valueOf(user.getId()),SecurityUtils.getSubject().getPrincipals());
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//赋予角色
for(RoleDto role:user.getRoles()){
info.addRole(role.getName());
}
//赋予权限
for(PermissionDto permission:user.getPermissions()){
//System.out.println(permission.getName());
info.addStringPermission(permission.getName());
}
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
String userName = token.getUsername();
User user = userDao.findUserByUsername(userName);
UserDto userDto = convertToDto(user);
if(user != null){
//登陆成功
Session session = SecurityUtils.getSubject().getSession();
session.setAttribute("user",userDto);
return new SimpleAuthenticationInfo(
userName, //用户
user.getPassword(), //密码
getName() //realm name
);
} else {
throw new UnknownAccountException();
}
}
Bean(name = "shiroFilter")
public ShiroFilterFactoryBean shiroFilterFactoryBean(){
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager());
Map<String, Filter> filters = new LinkedHashMap<String,Filter>();
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setRedirectUrl("/login");
shiroFilterFactoryBean.setFilters(filters);
shiroFilterFactoryBean.setLoginUrl("/notAuthc");
Map<String,String> filterChainDefinitionManager = new LinkedHashMap<String,String>();
filterChainDefinitionManager.put("/logout","logout");
filterChainDefinitionManager.put("/userInfo","authc");
filterChainDefinitionManager.put("/jobs/**","perms[WORDCOUNT:CREATE]");
filterChainDefinitionManager.put("/admin/**","roles[Admin]");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionManager);
shiroFilterFactoryBean.setSuccessUrl("/");
shiroFilterFactoryBean.setUnauthorizedUrl("/notAuthz");
return shiroFilterFactoryBean;
}
const getters = {
status: state => state.user.status,
username: state => state.user.username,
name: state => state.user.name,
roles: state => state.user.roles,
addRouters: state => state.permission.addRouters
}
{
path: "/admin",
component: _import('admin/index'),
//redirect: '/dashboard',
meta:{
role: ['Admin']
},
name: "admin"
}
function filterAsyncRouter(asyncRouterMap,roles) {
const accessedRouters = asyncRouterMap.filter(route => {
if(hasPermission(roles,route)){
if(route.children && route.children.length){
route.children = filterAsyncRouter(route.children,roles)
}
return true
}
return false
})
return accessedRouters
}
@Bean(name = "sessionManager")
public DefaultWebSessionManager sessionManager(){
DefaultWebSessionManager manager = new DefaultWebSessionManager();
//manager.setCacheManager(cacheManager);// 加入缓存管理器
manager.setSessionFactory(shiroSessionFactory());//设置sessionFactory
manager.setSessionDAO(shiroSessionDao());// 设置SessionDao
manager.setDeleteInvalidSessions(true);// 删除过期的session
manager.setGlobalSessionTimeout(shiroSessionDao().getExpireTime());// 设置全局session超时
时间
manager.setSessionValidationSchedulerEnabled(true);// 是否定时检查session
return manager;
}
@Override
protected Serializable doCreate(Session session) {
Serializable sessionId = this.generateSessionId(session);
assignSessionId(session,sessionId);
Jedis jedis = null;
try{
jedis = jedisPool.getResource();
//session由Redis缓存失效决定,这里作简单标识
session.setTimeout(expireTime);
jedis.setex(prefix + sessionId, expireTime, SerializeUtils.serializaToString((ShiroSession) session));
logger.info("sessionId {} name {} 被创建", sessionId, session.getClass().getName());
}catch (Exception e){
logger.warn("创建session失败",e);
}finally {
jedis.close();
}
return sessionId;
}
@bean
public SparkConf sparkConf() {
SparkConf sparkConf = new SparkConf()
.setAppName(appName)
.setMaster("local");
return sparkConf;
}
如题
Spark与Spring Boot集成的关键是能够在Spring的容器中提供一个Spark的入口。
SparkContext是Spark的入口,是程序与Spark集群交互的桥梁。在Spark 2.0引入了SparkSession,为用户提供了一个更加统一的切入点来使用Spark的各项功能,并且允许用户通过调用DataFrame和DataSet相关API来编写Spark程序,在本例中我们采用SparkSession来作为Spark的入口。
SparkSession依赖于SparkContext,而SparkContext依赖于SparkConf。因此我们创建这三个对象,并以Bean的形式存放到Spring的容器之中。
以SparkSession为例
@Bean
public SparkSession sparkSession(){
return SparkSession
.builder()
.sparkContext(javaSparkContext().sc())
.appName("Java Spark SQL basic example")
.getOrCreate();
}
Spark提供了面向Java的Api,所以我们可以直接拿来用。
我们在SpringBoot的Configuration Class声明SparkSession、SparkContext、SparkConf这三个Bean,使得容器在启动时创建这三个对象。
我们在Service层注入SparkSession,就可以顺利使用Spark的各项功能了。
@Autowired
private SparkSession sparkSession;
List<Word> wordList = Arrays.stream(tempWords).map(Word::new).collect(Collectors.toList());
dataFrame = sparkSession.createDataFrame(wordList,Word.class);
dataFrame.show();
创建DataFrame
RelationalGroupedDataset groupedDataset = dataFrame.groupBy(col("word"));
List<Row> rows = groupedDataset.count().collectAsList();
return rows.stream().map(new Function<Row, Count>() {
@Override
public Count apply(Row row) {
return new Count(row.getString(0),row.getLong(1));
}
}).sorted(new CountComparator()).collect(Collectors.toList());
Count
详情请见WordCount
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
@JoinTable(name = "user_role",
joinColumns = {@JoinColumn(name = "userId",referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "roleId",referencedColumnName = "id")})
private List<Role> roles = new ArrayList<>();
@ManyToMany(cascade = CascadeType.MERGE, fetch = FetchType.LAZY)
@JoinTable(name = "user_permission",
joinColumns = {@JoinColumn(name = "userId",referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "permissionId",referencedColumnName = "id")})
private List<Permission> permissions = new ArrayList<>();
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
private List<User> users = new ArrayList<>();
@ManyToMany(cascade = CascadeType.MERGE,fetch = FetchType.LAZY)
@JoinTable(name = "role_permission",
joinColumns = {@JoinColumn(name = "roleId",referencedColumnName = "id")},
inverseJoinColumns = {@JoinColumn(name = "permissionId",referencedColumnName = "id")})
@CollectionId(columns = @Column(name = "id"),
type = @Type(type = "long"),
generator = "identity")
private List<Permission> permissions = new ArrayList<>();
@ManyToMany(mappedBy = "permissions",fetch = FetchType.LAZY)
private List<Role> roles = new ArrayList<>();
@ManyToMany(mappedBy = "permissions",fetch = FetchType.LAZY)
private List<User> users = new ArrayList<>();
Subject subject = SecurityUtils.getSubject();
subject.login(token);
@Bean(name = "securityManager")
public DefaultWebSecurityManager securityManager(){
DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
//设置Realm
securityManager.setRealm(shiroRealm());
//设置session管理器
securityManager.setSessionManager(sessionManager());
return securityManager;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//赋予角色和权限
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
throws AuthenticationException {
//用户认证
}
filterChainDefinitionManager.put("/userInfo","authc"); //需要登录
filterChainDefinitionManager.put("/jobs/**","perms[JOB:CREATE]"); //需要[JOB:CREATE]权限
filterChainDefinitionManager.put("/admin/**","roles[Admin]"); //需要Admin角色
如题
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.