springboot的使用03
SpringSecurity
引入相关依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
加入配置类
@EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter{ //请求授权的规则 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") .antMatchers("/level2/**").hasRole("vip2") .antMatchers("/level3/**").hasRole("vip3"); http.formLogin(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3") .and() .withUser("lzh").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2") .and() .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1"); } }
SpringShiro的使用
1.导入依赖
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.4.1</version> </dependency>
2.自定义userRealm
public class UserRealm extends AuthorizingRealm { @Autowired private UserService userService; //授权 @Override protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) { SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //拿到当前登录的这个对象 Subject subject = SecurityUtils.getSubject(); User currentUser = (User) subject.getPrincipal(); info.addStringPermission(currentUser.getPerem()); return info; } //认证 @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException { System.out.println("执行了=》"); UsernamePasswordToken userToken = (UsernamePasswordToken)token; User user = userService.selectUser(((UsernamePasswordToken) token).getUsername()); if(user == null){ return null; } return new SimpleAuthenticationInfo(user,user.getPassword(),""); } }
3.配置shiroConfig
@Configuration public class ShiroConfig { @Bean public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager securityManager){ ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(securityManager); //添加shiro的内置过滤器 /* anon : 无需认证就可以访问 authc:必须认证才可以访问 user: 必须有记住我功能才能用 perms: 拥有对某个资源的权限才能访问 role: 拥有某个角色权限才能访问 */ Map<String,String> filterMap = new LinkedHashMap<>(); filterMap.put("/add","perms[user:add]"); filterMap.put("/update","perms[user:update]"); bean.setFilterChainDefinitionMap(filterMap); bean.setLoginUrl("/toLogin");//当没有认证时,就会跳到登录页面 bean.setUnauthorizedUrl("/unauth"); return bean; } @Bean("securityManager") public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){ DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager(); securityManager.setRealm(userRealm); return securityManager; } //创建realm对象,需要自定义类 @Bean public UserRealm userRealm(){ UserRealm bean = new UserRealm(); return bean; } }
4.controller方法
@RequestMapping("/login") public String login(String username , String password,Model model){ //获取当前的用户 Subject subject = SecurityUtils.getSubject(); //封装用户的登录数据 UsernamePasswordToken token = new UsernamePasswordToken(username,password); try{ subject.login(token); return "index"; }catch (UnknownAccountException e){ model.addAttribute("msg","用户名错误"); return "login"; }catch (IncorrectCredentialsException e){ model.addAttribute("msg","密码错误"); return "login"; } //执行登陆方法,如果没有异常就说明OK了. }
springboot的异步任务
1.在异步任务上加一个@Async注解然后在启动类上加@EnableAsync注解
springboot的定时任务
1.在定时任务上加一个@Scheduled注解然后在启动类上加@EnableScheduling注解
springboot整合Redis
在springboot2.0之后,jedis被改成了lettuce
jedis:采用的直连,多个线程操作的话,是不安全的,如果想要避免不安全的,使用jedis pool连接池。BIO
lettuce:采用netty,实例可以在多个线程中进行共享,不存在线程不安全的情况.可以减少线程数据. NIO
1.导入redis的依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2.编写redis的配置类
public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> template = new RedisTemplate<String, Object>(); template.setConnectionFactory(factory); Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); // key采用String的序列化方式 template.setKeySerializer(stringRedisSerializer); // hash的key也采用String的序列化方式 template.setHashKeySerializer(stringRedisSerializer); // value序列化方式采用jackson template.setValueSerializer(jackson2JsonRedisSerializer); // hash的value序列化方式采用jackson template.setHashValueSerializer(jackson2JsonRedisSerializer); template.afterPropertiesSet(); return template; } }