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);
}
