redis缓存
使用redis 1、在pom.xml中加依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 2、解决乱码 在config包下,加配置文件 /** * 解决redis乱码 */ @Configuration public class RedisTemplateConfig { @Autowired private RedisTemplate redisTemplate; @Bean public RedisTemplate<String, Object> redisTemplate() { // key序列化 redisTemplate.setKeySerializer(new StringRedisSerializer()); //val实例化 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } 3、在application.yml中加配置文件 spring: redis: host: 127.0.0.1 4、引用redis工具 @Autowired private RedisTemplate redisTemplate; 5、实例 public Article findById(String id) { //先从缓存中查询当前对象 Article article = (Article) redisTemplate.opsForValue().get("article_" + id); //如果没有取到 if(article == null){ //从数据库中查询 article = articleDao.findById(id).get(); //存入到缓存中 redisTemplate.opsForValue().set("article_" + id, article); //演示设置过期时间 //redisTemplate.opsForValue().set("article_" + id, article, 10, TimeUnit.HOURS); } return article; } public void deleteById(String id) { redisTemplate.delete("article_" + id); articleDao.deleteById(id); }
springboot自带缓存
1、在启动类上加注解 @EnableCaching 2、(存)实例 @Cacheable(value = "gathering", key = "#id") public Gathering findById(String id) { return gatheringDao.findById(id).get(); } 3、(删)实例 @CacheEvict(value = "gathering", key = "#gathering.id") public void update(Gathering gathering) { gatheringDao.save(gathering); }
rabbitmq消息
生产者: 1、加入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> 2、配置文件 spring: rabbitmq: host: 127.0.0.1 3、注入工具类 @Autowired private RabbitTemplate rabbitTemplate; 4、发送消息 Map<String, String> map = new HashMap<>(); map.put("mobile", mobile); map.put("checkcode", checkcode); rabbitTemplate.convertAndSend("sms", map); 消费者: 1、加入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> 2、配置文件 spring: rabbitmq: host: 127.0.0.1 3、消费消息 @Component @RabbitListener(queues = "sms") public class SmsListener { @RabbitHandler public void executeSms(Map<String, String> map){ System.out.println("手机号:" + map.get("mobile")); System.out.println("验证码:" + map.get("checkcode")); } }
security密码加密
1、加入依赖 <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> 2、添加config配置文件 /** * 安全配置类 */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter{ @Override protected void configure(HttpSecurity http) throws Exception { /** * authorizeRequests所有security全注解配置实现的开端,表示开始说明需要的权限。 * 需要的权限分两部分,第一部分是拦截的路径,第二部分是访问该路径需要的权限。 * antMatchers表示拦截什么路径,permitAll任何权限都可以访问,直接放行所有。 * anyRequest任何的请求,authenticated认证后才可访问。 * and().csrf().disable()固定写法,表示使csrf拦截失效。 */ http .authorizeRequests() .antMatchers("/**").permitAll() .anyRequest().authenticated() .and().csrf().disable(); } } 3、在启动类上注入bean @Bean public BCryptPasswordEncoder encoder(){ return new BCryptPasswordEncoder(); } 4、在业务层注入工具类 @Autowired private BCryptPasswordEncoder encoder; 5、加密 //密码加密 user.setPassword(encoder.encode(user.getPassword())); 6、解密 public User login(String mobile, String password) { User user = userDao.findByMobile(mobile); if(user != null && encoder.matches(password, user.getPassword())){ return user; } return null; }
jwt验证
1、配置文件添加
jwt:
config:
key: zhang.Mr //签名关键字(自定义)
ttl: 3600000 //失效时间
2、注入依赖 @Autowired private JwtUtil jwtUtil;
3、生成令牌,并返回给前端 @PostMapping("/login") public Result login(@RequestBody Admin admin){ admin = adminService.login(admin); if(admin == null){ return new Result(false, StatusCode.LOGINERROR, "登录失败"); } // 使得前后端可以通话的操作,采用JWT来实现 // 生成令牌 String token = jwtUtil.createJWT(admin.getId(), admin.getLoginname(), "admin"); Map<String, Object> map = new HashMap<>(); map.put("token", token); map.put("role", "admin"); return new Result(true, StatusCode.OK, "登录成功", map); }
4、管理员携带令牌删除用户(配置拦截器)
4.1 先编写config
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {
@Autowired
private JwtInterceptor jwtInterceptor;
@Override
protected void addInterceptors(InterceptorRegistry registry) {
//注册拦截器要声明拦截器对象和拦截的请求
registry.addInterceptor(jwtInterceptor)
.addPathPatterns("/**") //拦截所有请求
.excludePathPatterns("/**/login/**"); //该请求除外
}
}
4.2 编写拦截器
@Component
public class JwtInterceptor implements HandlerInterceptor {
@Autowired
private JwtUtil jwtUtil;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//无论任何都放行,具体能不能操作还是在具体的操作中去判断
//拦截器只是负责把请求头中包含token的令牌进行一个解析验证
String header = request.getHeader("Authorization");
if(header!=null && !"".equals(handler)){
//如果包含有Authorization头信息,就对其进行解析
if(header.startsWith("Bearer ")){
//得到token
String token = header.substring(7);
//对令牌进行验证
try{
Claims claims = jwtUtil.parseJWT(token);
String roles = (String) claims.get("roles");
if(roles != null && roles.equals("admin")){
request.setAttribute("claims_admin", token);
}
if(roles != null && roles.equals("user")){
request.setAttribute("claims_user", token);
}
}catch (Exception e){
throw new RuntimeException("令牌不正确!");
}
}
}
return true;
}
}
4.3 业务层进行操作
public void deleteById(String id) {
String token = (String) request.getAttribute("claims_admin");
if(token == null || "".equals(token)){
throw new RuntimeException("权限不足!");
}
userDao.deleteById(id);
}