当前位置:   article > 正文

spring配置redis的单元测试(spring-test,junit)_@runwith(redistest.class)

@runwith(redistest.class)

使用的包:

  1. <dependency>
  2. <groupId>org.springframework</groupId>
  3. <artifactId>spring-test</artifactId>
  4. <version>3.1.2.RELEASE</version>
  5. <scope>test</scope>
  6. </dependency>
  7. <dependency>
  8. <groupId>junit</groupId>
  9. <artifactId>junit</artifactId>
  10. <version>4.8.2</version>
  11. <scope>test</scope>
  12. </dependency>
  1. <dependency>
  2. <groupId>org.springframework.data</groupId>
  3. <artifactId>spring-data-redis</artifactId>
  4. <version>1.7.11.RELEASE</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>redis.clients</groupId>
  8. <artifactId>jedis</artifactId>
  9. <version>2.9.0</version>
  10. </dependency>



redis数据库参数:

  1. ###Redis缓存配置
  2. #缓存池最小空闲数
  3. redis.minIdle=5
  4. #缓存池最大空闲数
  5. redis.maxIdle=100
  6. #缓存池最大连接数
  7. redis.maxTotal=300
  8. #最大等待时间
  9. redis.maxWaitMillis=3000
  10. #使用连接时是否测试可用
  11. redis.testOnBorrow=true
  12. #主机地址
  13. redis.host=127.0.0.1
  14. #主机端口
  15. redis.port=6379
  16. #主机密码
  17. redis.password=123456
  18. #数据库下标
  19. redis.database=4

redis.xml的配置,这里只有redis简单的配置,关于spring另外配置,

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache"
  3. xsi:schemaLocation="http://www.springframework.org/schema/beans
  4. http://www.springframework.org/schema/beans/spring-beans.xsd
  5. http://www.springframework.org/schema/cache
  6. http://www.springframework.org/schema/cache/spring-cache-3.2.xsd">
  7. <!-- redis pool相关配置 -->
  8. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  9. <!-- 最小空闲数 -->
  10. <property name="minIdle" value="${redis.minIdle}" />
  11. <!-- 最大空闲数 -->
  12. <property name="maxIdle" value="${redis.maxIdle}" />
  13. <!-- 最大连接数 -->
  14. <property name="maxTotal" value="${redis.maxTotal}" />
  15. <!-- 最大等待时间 单位毫秒(ms) -->
  16. <property name="maxWaitMillis" value="${redis.maxWaitMillis}" />
  17. <!-- 使用连接时测试连接是否可用 -->
  18. <property name="testOnBorrow" value="${redis.testOnBorrow}" />
  19. </bean>
  20. <!-- jedis客户端连接工厂 -->
  21. <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  22. <property name="poolConfig" ref="poolConfig" />
  23. <property name="database" value="${redis.database}" />
  24. <property name="port" value="${redis.port}" />
  25. <property name="hostName" value="${redis.host}" />
  26. <property name="password" value="${redis.password}" />
  27. </bean>
  28. <!-- redisTemplate模板 -->
  29. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  30. <property name="connectionFactory" ref="jedisConnectionFactory" />
  31. </bean>
  32. </beans>
redis的实现代码,使用了redisTemplate,这里基本代码学习的一个网友的

  1. package org.gyy.entity.user;
  2. import java.io.Serializable;
  3. public class User implements Serializable{
  4. /**
  5. *
  6. */
  7. private static final long serialVersionUID = -5528480600517508340L;
  8. private String id;
  9. private String name;
  10. private String password;
  11. public User() {
  12. super();
  13. }
  14. public User(String id, String name, String password) {
  15. super();
  16. this.id = id;
  17. this.name = name;
  18. this.password = password;
  19. }
  20. public String getId() {
  21. return id;
  22. }
  23. public void setId(String id) {
  24. this.id = id;
  25. }
  26. public String getName() {
  27. return name;
  28. }
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32. public String getPassword() {
  33. return password;
  34. }
  35. public void setPassword(String password) {
  36. this.password = password;
  37. }
  38. @Override
  39. public String toString() {
  40. return "User [id=" + id + ", name=" + name + ", password=" + password + "]";
  41. }
  42. }
  1. package org.gyy.redis;
  2. import javax.annotation.Resource;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.data.redis.serializer.RedisSerializer;
  5. public abstract class AbstractBaseRedisDao<K,V> {
  6. @Resource
  7. protected RedisTemplate<K, V> redisTemplate;
  8. /**
  9. * 得到RedisSerializer
  10. * @return
  11. */
  12. public RedisSerializer<String> getRedisSerializer() {
  13. return redisTemplate.getStringSerializer();
  14. }
  15. /**
  16. * 设置redis
  17. * @param redisTemplate
  18. */
  19. public void setRedisTemplate(RedisTemplate<K, V> redisTemplate) {
  20. this.redisTemplate = redisTemplate;
  21. }
  22. }
  1. package org.gyy.redis.dao;
  2. import java.util.List;
  3. import org.gyy.entity.user.User;
  4. import org.gyy.redis.AbstractBaseRedisDao;
  5. import org.springframework.dao.DataAccessException;
  6. import org.springframework.data.redis.connection.RedisConnection;
  7. import org.springframework.data.redis.core.RedisCallback;
  8. import org.springframework.data.redis.serializer.RedisSerializer;
  9. import org.springframework.stereotype.Component;
  10. import org.springframework.util.Assert;
  11. @Component
  12. public class UserDao extends AbstractBaseRedisDao<String, User> implements IUserDao {
  13. @Override
  14. public boolean add(User user) {
  15. // TODO Auto-generated method stub
  16. boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
  17. @Override
  18. public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
  19. // TODO Auto-generated method stub
  20. RedisSerializer<String> serializer = getRedisSerializer();
  21. byte[] key = serializer.serialize(user.getId());
  22. byte[] name = serializer.serialize(user.getName());
  23. return connection.setNX(key, name);
  24. }
  25. });
  26. return result;
  27. }
  28. @Override
  29. public boolean add(List<User> list) {
  30. // TODO Auto-generated method stub
  31. Assert.notEmpty(list);
  32. boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
  33. @Override
  34. public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
  35. // TODO Auto-generated method stub
  36. RedisSerializer<String> serializer = getRedisSerializer();
  37. for (User user : list) {
  38. byte[] key = serializer.serialize(user.getId());
  39. byte[] name = serializer.serialize(user.getName());
  40. connection.setNX(key, name);
  41. }
  42. return true;
  43. }
  44. },false,true);
  45. return result;
  46. }
  47. @Override
  48. public void delete(String key) {
  49. // TODO Auto-generated method stub
  50. redisTemplate.delete(key);
  51. }
  52. @Override
  53. public void delete(List<String> keys) {
  54. // TODO Auto-generated method stub
  55. redisTemplate.delete(keys);
  56. }
  57. @Override
  58. public boolean update(User user) {
  59. // TODO Auto-generated method stub
  60. String keyId = user.getId();
  61. if (get(keyId) == null) {
  62. throw new NullPointerException("数据行不存在:key="+keyId);
  63. }
  64. boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
  65. @Override
  66. public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
  67. // TODO Auto-generated method stub
  68. RedisSerializer<String> serializer = getRedisSerializer();
  69. byte[] keyId = serializer.serialize(user.getId());
  70. byte[] name = serializer.serialize(user.getName());
  71. connection.set(keyId, name);
  72. return true;
  73. }
  74. });
  75. return result;
  76. }
  77. @Override
  78. public User get(String keyId) {
  79. // TODO Auto-generated method stub
  80. User result = redisTemplate.execute(new RedisCallback<User>() {
  81. @Override
  82. public User doInRedis(RedisConnection connection) throws DataAccessException {
  83. // TODO Auto-generated method stub
  84. RedisSerializer<String> serializer = getRedisSerializer();
  85. byte[] key = serializer.serialize(keyId);
  86. byte[] value = connection.get(key);
  87. if (null == value) {
  88. return null;
  89. }
  90. String name = serializer.deserialize(value);
  91. return new User(keyId,name,null);
  92. }
  93. });
  94. return result;
  95. }
  96. }
后面的测试部分使用的是spring-test和junit4做的单元测试,以前没有注意,突然觉得spring-test很安逸

  1. package org.gyy.baseTest;
  2. import org.junit.runner.RunWith;
  3. import org.springframework.test.context.ContextConfiguration;
  4. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  5. @RunWith(SpringJUnit4ClassRunner.class)//使用junit4进行测试
  6. @ContextConfiguration({"classpath*:applicationContext.xml"}) //加载配置文件
  7. //------------如果加入以下代码,所有继承该类的测试类都会遵循该配置,也可以不加,在测试类的方法上///控制事务,参见下一个实例
  8. //这个非常关键,如果不加入这个注解配置,事务控制就会完全失效!
  9. //@Transactional
  10. //这里的事务关联到配置文件中的事务控制器(transactionManager = "transactionManager"),同时//指定自动回滚(defaultRollback = true)。这样做操作的数据才不会污染数据库!
  11. //@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
  12. //------------
  13. public class BaseJunit4Test {
  14. }

  1. package org.gyy.redis;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.annotation.Resource;
  5. import org.gyy.baseTest.BaseJunit4Test;
  6. import org.gyy.entity.user.User;
  7. import org.gyy.redis.dao.IUserDao;
  8. import org.junit.Test;
  9. import org.springframework.test.annotation.Rollback;
  10. import org.springframework.transaction.annotation.Transactional;
  11. import junit.framework.Assert;
  12. public class RedisTest extends BaseJunit4Test{
  13. @Resource
  14. private IUserDao userDao;
  15. @Test//标明是测试方法
  16. @Transactional //标明此方法需使用事务
  17. @Rollback(true)//标明使用完此方法后事务不回滚,true时为回滚
  18. public void addUser(){
  19. User user = new User("12345","张三",null);
  20. boolean result = userDao.add(user);
  21. Assert.assertTrue("插入失败",result);
  22. System.out.println("你好");
  23. }
  24. @Test
  25. public void testGetUser(){
  26. String key = "12";
  27. User user = userDao.get(key);
  28. Assert.assertNotNull(user);
  29. Assert.assertEquals(user.getName(), "李四");
  30. System.out.println(user);
  31. }
  32. @Test
  33. public void testAddUserList(){
  34. List list = new ArrayList<>();
  35. for (int i = 0; i < 10; i++) {
  36. User user = new User();
  37. user.setId("1"+i);
  38. user.setName("张三"+i);
  39. list.add(user);
  40. }
  41. long begin = System.currentTimeMillis();
  42. boolean result = userDao.add(list);
  43. System.out.println(System.currentTimeMillis()-begin);
  44. Assert.assertTrue(result);
  45. }
  46. @Test
  47. public void testUpdata(){
  48. User user = new User("12", "李四", null);
  49. boolean update = userDao.update(user);
  50. System.out.println(update);
  51. }
  52. }






声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Gausst松鼠会/article/detail/160037?site
推荐阅读
相关标签
  

闽ICP备14008679号