并发用户在插入记录时给出死锁

时间:2017-04-05 09:30:38

标签: hibernate spring-boot

我正在使用jmeter进行测试,当超过5个用户登录并使用hibernate插入记录时,我得到了引发:

com.mysql.jdbc.exceptions.jdbc4.MySQLTransactionRollbackException: Deadlock found when trying to get lock; try restarting transaction

登录后,我使用userId,usernam e和创建日期创建令牌,并使用此userId从令牌和插入记录中获取用户ID。

代币

if (authToken != null) {
            String userName = tokenUtils.getUsernameFromToken(authToken);
            beanConfig.setConfig(authToken);
            /*Set<String> roles = tokenUtils.getUserRoleFromToken(authToken);
            CustomSecurityContext.setUserRoleSet(roles);*/
            UserDTO userDto = new UserDTO();
            userDto.setUsername(userName);
            if (userName != null && tokenUtils.validateToken(authToken, userDto).booleanValue()) {
                logger.info("token validate....:" + userName);
                filterChain.doFilter(request, response);
                return;

            } else {
                // Removing entry for token in TokenIdleTimeMap used for
                // tracking idle time expiration date
                tokenUtils.removeEntryFromTokenIdleTimeMap(authToken);
                logger.info("Token Expired or session time out please login again>>>>>>>");
                httpResponse.setContentType("application/json");
                httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                httpResponse.getWriter().write(sendApiResponse());
                return;
            }

        }
        filterChain.doFilter(request, response);
        return;
    } 

和存储库

  try{
        Query query = sessionFactory.getCurrentSession().createQuery("update User P set P.goalSettingProgress =:goalSettingStatus where P.id =:empId");
        query.setString("goalSettingStatus", status);
        query.setInteger("empId", empId);
        query.executeUpdate();
    }catch(Exception ex){
        logger.info("Esception occurred while updating goal setting status: "+ ex.getMessage());
        ex.printStackTrace();
        throw new UserException(UserErrorCodes.DATA_NOT_SAVED, ex.getMessage());

    }      

我在.xml文件中进行所有配置,因此下面是web.xml

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>PAMS</display-name>
   <welcome-file-list>
    <welcome-file>/</welcome-file>
  </welcome-file-list>
  <context-param>
    <param-name>contextConfigLocation</param-name> 
    <param-value>/WEB-INF/springConfig-servlet.xml,/WEB-INF/PAMSSecurity.xml,/WEB-INF/spring-beans.xml</param-value>
  </context-param>
  <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
         <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param> 
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!-- Map all requests to the DispatcherServlet for handling -->
    <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

   <filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <listener>
    <listener-class>
      org.springframework.security.web.session.HttpSessionEventPublisher
    </listener-class>
  </listener>
  <filter>
    <filter-name>CorsFilter</filter-name>
    <filter-class>com.vl.pam.filter.CorsFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>CorsFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

Below is security.xml 

<beans:bean id="concurrencyFilter"
        class="org.springframework.security.web.session.ConcurrentSessionFilter">
        <beans:property name="sessionRegistry" ref="sessionRegistry" />
        <beans:property name="expiredUrl" value="/session-expired.htm" />
    </beans:bean>


    <beans:bean id="sas"
        class="org.springframework.security.web.authentication.session.ConcurrentSessionControlStrategy">
        <beans:constructor-arg name="sessionRegistry"
            ref="sessionRegistry" />
        <beans:property name="maximumSessions" value="1" />
    </beans:bean>

    <!-- Successful Authentication Handler -->

    <beans:bean id="sessionRegistry"
        class="org.springframework.security.core.session.SessionRegistryImpl" />

    <!-- Request Filters -->
    <http auto-config="true" use-expressions="true" 
        authentication-manager-ref="authenticationManager">

        <custom-filter ref="authenticationTokenProcessingFilter"
            position="PRE_AUTH_FILTER" />
        <custom-filter position="CONCURRENT_SESSION_FILTER" ref="concurrencyFilter" />
        <intercept-url pattern="/logout" access="permitAll" />
        <session-management
            session-authentication-strategy-ref="sas" />

    </http>


    <authentication-manager id="authenticationManager"/>
         <!-- <authentication-provider user-service-ref="customUserDetailsService">
        </authentication-provider> 
    </authentication-manager>

    <beans:bean id="customUserDetailsService"
        class="com.vl.pam.service.CustomUserDetailsServiceImpl">
    </beans:bean>   -->

    <beans:bean id="authenticationTokenProcessingFilter"
        class="com.vl.pam.authentication.AuthenticationTokenProcessingFilter"></beans:bean>

    <beans:bean id="passwordEncoder"
        class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
    </beans:bean>

<!--    <beans:bean id="unauthorizedEntryPoint"
        class="com.vl.pam.authentication.UnauthorizedEntryPoint"></beans:bean> -->

</beans:beans>

以下是springConfig-servlet.xml

 <mvc:annotation-driven />
    <mvc:view-controller path="/" view-name="index" />
    <context:component-scan base-package="com.vl.pam"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="locations">
            <list>
            <value>classpath:application.properties</value>
                    <!-- <value>file:#{systemProperties.propertiesFilePath}/application.properties</value> -->
            </list>
        </property>
    </bean>


    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="20971520" />
    </bean>



    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <!-- <property name="dataSource" ref="dataSource" /> -->
        <property name="hibernateProperties">   
        <props>
                <!-- <prop key="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</prop> -->
                <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                <!-- <prop key="hibernate.connection.url"> jdbc:sqlserver://10.10.52.195:1433;databaseName=pamsvaluelabs_erpportal</prop> -->
                <prop key="hibernate.connection.url"> jdbc:mysql://10.10.53.221:3306/PAMS_DEV</prop>
                <!-- <prop key="hibernate.connection.username">pamstestuser</prop>
                <prop key="hibernate.connection.password">Value*123</prop> -->
                <prop key="hibernate.connection.username">root</prop>
                <prop key="hibernate.connection.password">Secure@789</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>  
                <!-- <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop> -->
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.c3p0.min_size">5</prop>
                <prop key="hibernate.c3p0.max_size">20</prop>
                <prop key="hibernate.c3p0.timeout">300</prop>
                <prop key="hibernate.c3p0.max_statements">50</prop>
                <prop key="hibernate.c3p0.idle_test_period">3000</prop>
                <prop key="hibernate.show_sql">false</prop>
                <prop key="hibernate.c3p0.acquire_increment">1</prop>
                <prop key="hibernate.c3p0.numHelperThreads">6</prop> 

            </props>            
        </property>

        <property name="mappingJarLocations">
            <list>
            </list>
        </property>

        <property name="packagesToScan">
            <list>
            <value>com.vl.pam.model</value>
            </list>
        </property>

    </bean>
    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

     <tx:advice id="transactionAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED" />
            <tx:method name="save*" propagation="REQUIRED" />
            <tx:method name="update*" propagation="REQUIRED" />
            <tx:method name="modify*" propagation="REQUIRED" />
            <tx:method name="edit*" propagation="REQUIRED" />
            <tx:method name="saveOrUpdate*" propagation="REQUIRED" />
            <tx:method name="delete*" propagation="REQUIRED" />
            <tx:method name="remove*" propagation="REQUIRED" />
            <tx:method name="upload*" propagation="REQUIRED" />
            <tx:method name="roleEdit*" propagation="REQUIRED" />


            <tx:method name="post*" propagation="REQUIRED" read-only="true" />
            <tx:method name="get*" propagation="REQUIRED" read-only="true" />
            <tx:method name="find*" propagation="REQUIRED" read-only="true" />
            <tx:method name="load*" propagation="REQUIRED" read-only="true" />
            <tx:method name="search*" propagation="REQUIRED" read-only="true" />
            <tx:method name="datagrid*" propagation="REQUIRED"  read-only="true" />

            <tx:method name="*" propagation="REQUIRED" />
        </tx:attributes>
    </tx:advice> 


     <aop:config>
        <aop:pointcut id="transactionPointcut"
            expression="execution(* com.vl.pam.service.*.*(..)) || execution(* com.vl.pam.*.service.*.*(..))|| execution(* com.vl.pam.*.*(..)) || execution(* com.vl.pam.*.*(..))" />
        <aop:advisor pointcut-ref="transactionPointcut"
            advice-ref="transactionAdvice" />
    </aop:config>  



     <bean id="httpComponentsClientHttpRequestFactory"
        class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory" />

    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
        <constructor-arg ref="httpComponentsClientHttpRequestFactory" />
    </bean>
</beans>

0 个答案:

没有答案