当前位置:首页 » 硬盘大全 » 单元测试spring缓存未拦截
扩展阅读
webinf下怎么引入js 2023-08-31 21:54:13
堡垒机怎么打开web 2023-08-31 21:54:11

单元测试spring缓存未拦截

发布时间: 2023-01-10 21:44:43

⑴ Spring本地缓存的使用方法

我们现在在用的Spring Cache,可以直接看Spring Boot提供的缓存枚举类,有如下这些:

EhCache:一个纯Java的进程内缓存框架,所以也是基于本地缓存的。(注意EhCache2.x和EhCache3.x相互不兼容)。
Redis:分布式缓存,只有Client-Server(CS)模式,Java一般使用Jedis/Luttuce来操纵。
Hazelcast:基于内存的数据网格。虽然它基于内存,但是分布式应用程序可以使用Hazelcast进行分布式缓存、同步、集群、处理、发布/订阅消息等。
Guava:它是Google Guava工具包中的一个非常方便易用的本地化缓存实现,基于LRU(最近最少使用)算法实现,支持多种缓存过期策略。在Spring5.X以后的版本已经将他标记为过期了。
Caffeine:是使用Java8对Guava缓存的重写版本,在Spring5中将取代了Guava,支持多种缓存过期策略。
SIMPLE:使用ConcurrentMapCacheManager,因为不支持缓存过期时间,所以做本地缓存基本不考虑该方式。

关于分布式缓存,我们需要后面会专门讨论Redis的用法,这里只看本地缓存。性能从高到低,依次是Caffeine,Guava,ConcurrentMapCacheManager,其中Caffeine在读写上都快了Guava近一倍。

这里我们只讨论在Spring Boot里面怎么整合使用Caffeine和EhCache。

主要有以下几个步骤:

1)加依赖包:

2)配置缓存:
这里有两种方法,通过文件配置或者在配置类里面配置,先看一下文件配置,我们可以写一个properties文件,内容像这样:

然后还要在主类中加上@EnableCaching注解:

另外一种更灵活的方法是在配置类中配置:

应用类:

测试类:

导入依赖包,分为2.x版本和3.x版本。
其中2.x版本做如下导入:

3.x版本做如下导入:

导包完成后,我们使用JCacheManagerFactoryBean + ehcache.xml的方式配置:

参考资料:

https://blog.csdn.net/f641385712/article/details/94982916

http://www.360doc.com/content/17/1017/20/16915_695800687.shtml

⑵ 如何在spring中使用缓存

在Spring缓存机制中,包括了两个方面的缓存操作:1.缓存某个方法返回的结果;2.在某个方法执行前或后清空缓存。
Spring仅仅是提供了对缓存的支持,但它并没有任何的缓存功能的实现,spring使用的是第三方的缓存框架来实现缓存的功能。其中,spring对EHCache提供了很好的支持。
参考博客:http://www.cnblogs.com/fysola/p/6378400.html

⑶ windows环境下Redis+Spring缓存实例

一、Redis了解

1.1、Redis介绍:

redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set –有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。

Redis数据库完全在内存中,使用磁盘仅用于持久性。相比许多键值数据存储,Redis拥有一套较为丰富的数据类型。Redis可以将数据复制到任意数量的从服务器。

1.2、Redis优点:

(1)异常快速:Redis的速度非常快,每秒能执行约11万集合,每秒约81000+条记录。

(2)支持丰富的数据类型:Redis支持最大多数开发人员已经知道像列表,集合,有序集合,散列数据类型。这使得它非常容易解决各种各样的问题,因为我们知道哪些问题是可以处理通过它的数据类型更好。

(3)操作都是原子性:所有Redis操作是原子的,这保证了如果两个客户端同时访问的Redis服务器将获得更新后的值。

(4)多功能实用工具:Redis是一个多实用的工具,可以在多个用例如缓存,消息,队列使用(Redis原生支持发布/订阅),任何短暂的数据,应用程序,如Web应用程序会话,网页命中计数等。

1.3、Redis缺点:

(1)单线程

(2)耗内存

二、64位windows下Redis安装

Redis官方是不支持windows的,但是Microsoft Open Tech group 在 GitHub上开发了一个Win64的版本,下载地址:https://github.com/MSOpenTech/redis/releases。注意只支持64位哈。

小宝鸽是下载了Redis-x64-3.0.500.msi进行安装。安装过程中全部采取默认即可。

安装完成之后可能已经帮你开启了Redis对应的服务,博主的就是如此。查看资源管理如下,说明已经开启:

已经开启了对应服务的,我们让它保持,下面例子需要用到。如果没有开启的.,我们命令开启,进入Redis的安装目录(博主的是C:Program FilesRedis),然后如下命令开启:

redis-server redis.windows.conf

OK,下面我们进行实例。

三、详细实例

本工程采用的环境:Eclipse + maven + spring + junit

3.1、添加相关依赖(spring+junit+redis依赖),pom.xml:

4.0.0 com.luo redis_project 0.0.1-SNAPSHOT 3.2.8.RELEASE 4.10 org.springframework spring-core ${spring.version} org.springframework spring-webmvc ${spring.version} org.springframework spring-context ${spring.version} org.springframework spring-context-support ${spring.version} org.springframework spring-aop ${spring.version} org.springframework spring-aspects ${spring.version} org.springframework spring-tx ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-web ${spring.version} junit junit ${junit.version} test org.springframework spring-test ${spring.version} test org.springframework.data spring-data-redis 1.6.1.RELEASE redis.clients jedis 2.7.3

3.2、spring配置文件application.xml:

<"1.0" encoding="UTF-8"> classpath:properties/*.properties

3.3、Redis配置参数,redis.properties:

#redis中心#绑定的主机地址redis.host=127.0.0.1#指定Redis监听端口,默认端口为6379redis.port=6379#授权密码(本例子没有使用)redis.password=123456 #最大空闲数:空闲链接数大于maxIdle时,将进行回收redis.maxIdle=100 #最大连接数:能够同时建立的“最大链接个数”redis.maxActive=300 #最大等待时间:单位msredis.maxWait=1000 #使用连接时,检测连接是否成功 redis.testOnBorrow=true#当客户端闲置多长时间后关闭连接,如果指定为0,表示关闭该功能redis.timeout=10000

3.4、添加接口及对应实现RedisTestService.Java和RedisTestServiceImpl.java:

package com.luo.service; public interface RedisTestService { public String getTimestamp(String param);}

package com.luo.service.impl; import org.springframework.stereotype.Service;import com.luo.service.RedisTestService; @Servicepublic class RedisTestServiceImpl implements RedisTestService { public String getTimestamp(String param) { Long timestamp = System.currentTimeMillis(); return timestamp.toString(); } }

3.5、本例采用spring aop切面方式进行缓存,配置已在上面spring配置文件中,对应实现为MethodCacheInterceptor.java:

package com.luo.redis.cache; import java.io.Serializable;import java.util.concurrent.TimeUnit;import org.aopalliance.intercept.MethodInterceptor;import org.aopalliance.intercept.MethodInvocation;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations; public class MethodCacheInterceptor implements MethodInterceptor { private RedisTemplate redisTemplate; private Long defaultCacheExpireTime = 10l; // 缓存默认的过期时间,这里设置了10秒 public Object invoke(MethodInvocation invocation) throws Throwable { Object value = null; String targetName = invocation.getThis().getClass().getName(); String methodName = invocation.getMethod().getName(); Object[] arguments = invocation.getArguments(); String key = getCacheKey(targetName, methodName, arguments); try { // 判断是否有缓存 if (exists(key)) { return getCache(key); } // 写入缓存 value = invocation.proceed(); if (value != null) { final String tkey = key; final Object tvalue = value; new Thread(new Runnable() { public void run() { setCache(tkey, tvalue, defaultCacheExpireTime); } }).start(); } } catch (Exception e) { e.printStackTrace(); if (value == null) { return invocation.proceed(); } } return value; } /** * 创建缓存key * * @param targetName * @param methodName * @param arguments */ private String getCacheKey(String targetName, String methodName, Object[] arguments) { StringBuffer sbu = new StringBuffer(); sbu.append(targetName).append("_").append(methodName); if ((arguments != null) && (arguments.length != 0)) { for (int i = 0; i < arguments.length; i++) { sbu.append("_").append(arguments[i]); } } return sbu.toString(); } /** * 判断缓存中是否有对应的value * * @param key * @return */ public boolean exists(final String key) { return redisTemplate.hasKey(key); } /** * 读取缓存 * * @param key * @return */ public Object getCache(final String key) { Object result = null; ValueOperations operations = redisTemplate .opsForValue(); result = operations.get(key); return result; } /** * 写入缓存 * * @param key * @param value * @return */ public boolean setCache(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations operations = redisTemplate .opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } public void setRedisTemplate( RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; }}

3.6、单元测试相关类:

package com.luo.baseTest; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; //指定bean注入的配置文件 @ContextConfiguration(locations = { "classpath:application.xml" }) //使用标准的JUnit @RunWith注释来告诉JUnit使用Spring TestRunner @RunWith(SpringJUnit4ClassRunner.class) public class SpringTestCase extends { }

package com.luo.service; import org.junit.Test;import org.springframework.beans.factory.annotation.Autowired; import com.luo.baseTest.SpringTestCase; public class RedisTestServiceTest extends SpringTestCase { @Autowired private RedisTestService redisTestService; @Test public void getTimestampTest() throws InterruptedException{ System.out.println("第一次调用:" + redisTestService.getTimestamp("param")); Thread.sleep(2000); System.out.println("2秒之后调用:" + redisTestService.getTimestamp("param")); Thread.sleep(11000); System.out.println("再过11秒之后调用:" + redisTestService.getTimestamp("param")); } }

3.7、运行结果:

四、源码下载:redis-project().rar

以上就是本文的全部内容,希望对大家的学习有所帮助。

⑷ spring boot单元测试spring context重复加载问题

在使用spring boot框架进行单元测试时,笔者遇到一个问题,每次执行单元测试类时都会重复加载spring上下文,而加载过程通常都非常耗时,这大大增加了整个单元测试的执行时间,加载过程类似下面的日志:

在查阅了相关资料后,发现是spring在执行单元测试时,会将spring相关配置作为一个唯一的key,将对应上下文放在缓存当中,也就是说,如果每个单元测试类的加载的配置相同,就只会加载一次上下文,而后的执行过程中会从缓存中提取上下文,那么,为什么我的单元测试会每次加载?原因是,我的单元测试继承了同一个基类,而这个基类使用了powermock,在spring的测试策略中,如果有mock存在,单元测试类每次都会重新加载上下文,可以参考[ https://github.com/spring-projects/spring-boot/issues/7174] 。

那么,如何解决呢?方法也很简单,在基类中去除powermock,在特定需要使用powermock的类中覆写配置,笔者原先的spring测试基类是这样的:

修改后变成这样:

然后,在需要使用powermock模拟静态方法的类中做如下配置:

这样,就可以使得不需要powermock的类使用缓存中的上下文,从而减少整个单元测试的执行时间。

⑸ springMVC的拦截器不拦截直接访问jsp的请求

你好,分享一下我的拦截器,多多指教,代码如下:

在spring的配置文件里面进行配置拦截器

<!-- 拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 对所有的请求拦截使用/**-->
<mvc:mapping path="/**" />
<ref bean="userAccessInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
<bean id="userAccessInterceptor"class="com.web.interceptor.UserAccessInterceptor"></bean>

拦截器如下设置,当用户未登录时,返回到登录页面
class UserAccessInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
//静态资源直接return true
if(handler instanceof ResourceHttpRequestHandler){
return true;
}
if(Utils.isNull(UserCookie.getApploginUserId())){
response.sendRedirect(request.getContextPath()+"/login.jsp");
return false;
}
return true;
}