分类 后端 下的文章

什么是JWT
Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).定义了一种简洁的,自包含的方法用于通信双方之间以JSON对象的形式安全的传递信息。因为数字签名的存在,这些信息是可信的,JWT可以使用HMAC算法或者是RSA的公私秘钥对进行签名。

JWT请求流程
前端 登录请求-》 后端 登录成功 给token 前端
前端 请求后台页面(带上token就完事了)-》 后端 (校验 判断七七八八的一桶操作 判断token是否有效 就完事了)

jwt 依赖

<dependency>
      <groupId>com.auth0</groupId>
      <artifactId>java-jwt</artifactId>
      <version>3.4.0</version>
</dependency>

在来2个注解

这个注解是跳过认证写在接口方法上面

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
    boolean required() default true;
}

这个注解就是访问这个时候就需要token

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
    boolean required() default true;
}

token的生成方法

案例代码,随便找个类放进去就行,静态也行能调用就好(这个加密看起来高大上其实吧也就那样 MD5在是爹)

public String getToken(User user) {
        String token="";
        token= JWT.create().withAudience(user.getId()) //这个是ID
                .sign(Algorithm.HMAC256(user.getPassword())); //这个是密码大哥
        return token;
    }

这个是拦截器呗(也就是过滤判断2个注解)

public class AuthenticationInterceptor implements HandlerInterceptor {
    @Autowired
    UserService userService;
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String token = httpServletRequest.getHeader("token");// 从 http 请求头中取出 token
        // 如果不是映射到方法直接通过
        if(!(object instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)object;
        Method method=handlerMethod.getMethod();
        //检查是否有passtoken注释,有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                // 执行认证
                if (token == null) {
                    throw new RuntimeException("无token,请重新登录");
                }
                // 获取 token 中的 user id
                String userId;
                try {
                    userId = JWT.decode(token).getAudience().get(0);
                } catch (JWTDecodeException j) {
                    throw new RuntimeException("401");
                }
                User user = userService.findUserById(userId);
                if (user == null) {
                    throw new RuntimeException("用户不存在,请重新登录");
                }
                // 验证 token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                } catch (JWTVerificationException e) {
                    throw new RuntimeException("401");
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, 
                                  HttpServletResponse httpServletResponse, 
                            Object o, ModelAndView modelAndView) throws Exception {

    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, 
                                          HttpServletResponse httpServletResponse, 
                                          Object o, Exception e) throws Exception {
    }

配置拦截器(在配置类上添加了注解@Configuration,标明了该类是一个配置类并且会将该类作为一个SpringBean添加到IOC容器内)

@Configuration
public class InterceptorConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authenticationInterceptor())
                .addPathPatterns("/**");    // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
    }
    @Bean
    public AuthenticationInterceptor authenticationInterceptor() {
        return new AuthenticationInterceptor();
    }
}

本来是lnmp php5.6
后来 改了 某个php7.x版本具体也忘记了,报错是这样的
访问就说无法连接数据库,去排查了数据库是正常的。
最后发现是 这个报错
config.inc.php 55行

  $db = new Typecho_Db('Mysql', 'typecho_');

改成这个就好了

$db = new Typecho_Db('Pdo_Mysql', 'typecho_');

Pdo_Mysql和mysql可以去查查看

@Target:注解的作用目标
@Target(ElementType.TYPE)——接口、类、枚举、注解
@Target(ElementType.FIELD)——字段、枚举的常量
@Target(ElementType.METHOD)——方法
@Target(ElementType.PARAMETER)——方法参数
@Target(ElementType.CONSTRUCTOR) ——构造函数
@Target(ElementType.LOCAL_VARIABLE)——局部变量
@Target(ElementType.ANNOTATION_TYPE)——注解
@Target(ElementType.PACKAGE)——包

@Retention:注解的保留位置
RetentionPolicy.SOURCE:这种类型的Annotations只在源代码级别保留,编译时就会被忽略,在class字节码文件中不包含。
RetentionPolicy.CLASS:这种类型的Annotations编译时被保留,默认的保留策略,在class文件中存在,但JVM将会忽略,运行时无法获得。
RetentionPolicy.RUNTIME:这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用。
@Document:说明该注解将被包含在javadoc中
@Inherited:说明子类可以继承父类中的该注解

作者:意识流丶
链接:https://www.jianshu.com/p/e88d3f8151db
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    public class Main {

    private static int THREAD_COUNT = 10;
    private static int ITEM_COUNT = 1000;

    private static ConcurrentHashMap<String, Long> getData(int count) {

return  LongStream.rangeClosed(1, count)
        .boxed().collect(Collectors.toConcurrentMap(i-> UUID.randomUUID().toString(), Function.identity(),(t1, t2)->t1,ConcurrentHashMap::new));
    }

    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMap<String, Long> stringLongConcurrentHashMap = getData(ITEM_COUNT-100);
        System.out.println("init siez:"+stringLongConcurrentHashMap.size());
        ForkJoinPool forkJoinPool = new ForkJoinPool(THREAD_COUNT);
        forkJoinPool.execute(()-> IntStream.rangeClosed(1,10).parallel().forEach(i->{
               

                int gap=ITEM_COUNT-stringLongConcurrentHashMap.size();
                System.out.println("gap siez:"+gap);

                stringLongConcurrentHashMap.putAll(getData(gap));

               
        }));
        forkJoinPool.shutdown();
        forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
        System.out.println("finish siez:"+stringLongConcurrentHashMap.size());



    }
}

上面没添加锁输出以下结果

init siez:900
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
gap siez:100
finish siez:1900

添加锁之后

public class Main {

    private static int THREAD_COUNT = 10;
    private static int ITEM_COUNT = 1000;

    private static ConcurrentHashMap<String, Long> getData(int count) {

return  LongStream.rangeClosed(1, count)
        .boxed().collect(Collectors.toConcurrentMap(i-> UUID.randomUUID().toString(), Function.identity(),(t1, t2)->t1,ConcurrentHashMap::new));
    }

    public static void main(String[] args) throws InterruptedException {
        ConcurrentHashMap<String, Long> stringLongConcurrentHashMap = getData(ITEM_COUNT-100);
        System.out.println("init siez:"+stringLongConcurrentHashMap.size());
        ForkJoinPool forkJoinPool = new ForkJoinPool(THREAD_COUNT);
        forkJoinPool.execute(()-> IntStream.rangeClosed(1,10).parallel().forEach(i->{
               synchronized (stringLongConcurrentHashMap){

                int gap=ITEM_COUNT-stringLongConcurrentHashMap.size();
                System.out.println("gap siez:"+gap);

                stringLongConcurrentHashMap.putAll(getData(gap));

               }
        }));
        forkJoinPool.shutdown();
        forkJoinPool.awaitTermination(1, TimeUnit.HOURS);
        System.out.println("finish siez:"+stringLongConcurrentHashMap.size());



    }
}

输出结果
init siez:900
gap siez:100
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
gap siez:0
finish siez:1000

下表把 jpa 做的各种查询规范都列出来了。 如果要做其他相关查询,按照表格中的规范设计接口方法即可。


关键词 举例 生成的JPQL 语句片段
And findByLastnameAndFirstname … where x.lastname = ?1 and x.firstname = ?2
Or findByLastnameOrFirstname … where x.lastname = ?1 or x.firstname = ?2
Is,Equals findByFirstname,
findByFirstnameIs,
findByFirstnameEquals
… where x.firstname = ?1
Between findByStartDateBetween … where x.startDate between ?1 and ?2
LessThan findByAgeLessThan … where x.age < ?1
LessThanEqual findByAgeLessThanEqual … where x.age ⇐ ?1
GreaterThan findByAgeGreaterThan … where x.age > ?1
GreaterThanEqual findByAgeGreaterThanEqual … where x.age >= ?1
After findByStartDateAfter … where x.startDate > ?1
Before findByStartDateBefore … where x.startDate < ?1
IsNull findByAgeIsNull … where x.age is null
IsNotNull,NotNull findByAge(Is)NotNull … where x.age not null
Like findByFirstnameLike … where x.firstname like ?1
NotLike findByFirstnameNotLike … where x.firstname not like ?1
StartingWith findByFirstnameStartingWith … where x.firstname like ?1 (parameter bound with appended %)
EndingWith findByFirstnameEndingWith … where x.firstname like ?1 (parameter bound with prepended %)
Containing findByFirstnameContaining … where x.firstname like ?1 (parameter bound wrapped in %)
OrderBy findByAgeOrderByLastnameDesc … where x.age = ?1 order by x.lastname desc
Not findByLastnameNot … where x.lastname <> ?1
In findByAgeIn(Collection<age> ages)</age> … where x.age in ?1
NotIn findByAgeNotIn(Collection<age> age)</age> … where x.age not in ?1
True findByActiveTrue() … where x.active = true
False findByActiveFalse() … where x.active = false
IgnoreCase findByFirstnameIgnoreCase … where UPPER(x.firstame) = UPPER(?1)