springboot连接redis单机

系统管理员 2022-04-15 05:46 406阅读 0赞

1.创建maven工程,添加依赖,pom文件内容如下

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.szcatic</groupId>
  5. <artifactId>springboot</artifactId>
  6. <version>0.0.1-SNAPSHOT</version>
  7. <packaging>war</packaging>
  8. <name>springboot</name>
  9. <url>http://maven.apache.org</url>
  10. <parent>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-parent</artifactId>
  13. <version>2.1.0.RELEASE</version>
  14. </parent>
  15. <dependencies>
  16. <dependency>
  17. <groupId>org.springframework.boot</groupId>
  18. <artifactId>spring-boot-starter-web</artifactId>
  19. </dependency>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-test</artifactId>
  23. <scope>test</scope>
  24. </dependency>
  25. <!-- junit5运行所需jar包 -->
  26. <dependency>
  27. <groupId>org.junit.jupiter</groupId>
  28. <artifactId>junit-jupiter-engine</artifactId>
  29. <scope>test</scope>
  30. </dependency>
  31. <dependency>
  32. <groupId>org.junit.platform</groupId>
  33. <artifactId>junit-platform-runner</artifactId>
  34. <scope>test</scope>
  35. </dependency>
  36. <!-- spring-boot-starter-jdbc -->
  37. <dependency>
  38. <groupId>org.springframework.boot</groupId>
  39. <artifactId>spring-boot-starter-jdbc</artifactId>
  40. </dependency>
  41. <!-- mysql-connector-java -->
  42. <dependency>
  43. <groupId>mysql</groupId>
  44. <artifactId>mysql-connector-java</artifactId>
  45. </dependency>
  46. <!-- spring-boot-starter-data-redis -->
  47. <dependency>
  48. <groupId>org.springframework.boot</groupId>
  49. <artifactId>spring-boot-starter-data-redis</artifactId>
  50. </dependency>
  51. <!-- jedis -->
  52. <dependency>
  53. <groupId>redis.clients</groupId>
  54. <artifactId>jedis</artifactId>
  55. </dependency>
  56. </dependencies>
  57. <properties>
  58. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  59. <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
  60. <java.version>1.8</java.version>
  61. <!-- 指定springboot入口类 -->
  62. <start-class>com.szcatic.Application</start-class>
  63. </properties>
  64. <build>
  65. <plugins>
  66. <plugin>
  67. <groupId>org.springframework.boot</groupId>
  68. <artifactId>spring-boot-maven-plugin</artifactId>
  69. <configuration>
  70. <source>1.8</source>
  71. <target>1.8</target>
  72. </configuration>
  73. </plugin>
  74. </plugins>
  75. </build>
  76. </project>

2.在文件application.properties中添加redis连接池配置

  1. # redis连接池配置
  2. # Redis数据库索引(默认为0)
  3. spring.redis.database=0
  4. # Redis服务器地址
  5. spring.redis.host=127.0.0.1
  6. # Redis服务器连接端口
  7. spring.redis.port=6379
  8. # Redis服务器连接密码(默认为空)
  9. spring.redis.password=
  10. # 连接池最大连接数(使用负值表示没有限制)
  11. spring.redis.pool.max-active=20
  12. # 连接池最大阻塞等待时间(使用负值表示没有限制)
  13. spring.redis.pool.max-wait=-1
  14. # 连接池中的最大空闲连接
  15. spring.redis.pool.max-idle=20
  16. # 连接池中的最小空闲连接
  17. spring.redis.pool.min-idle=0
  18. # 连接超时时间(毫秒)
  19. spring.redis.timeout=60000

3.自定义配置类RedisConfig.java

  1. package com.szcatic.configuration;
  2. import org.springframework.beans.factory.annotation.Value;
  3. import org.springframework.context.annotation.Bean;
  4. import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
  5. import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
  6. import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
  7. import org.springframework.data.redis.core.RedisTemplate;
  8. import org.springframework.data.redis.serializer.StringRedisSerializer;
  9. import org.springframework.stereotype.Component;
  10. import redis.clients.jedis.JedisPoolConfig;
  11. @Component
  12. public class RedisConfig {
  13. @Value("${spring.redis.database}")
  14. private int database;
  15. @Value("${spring.redis.host}")
  16. private String host;
  17. @Value("${spring.redis.port}")
  18. private int port;
  19. @Value("${spring.redis.timeout}")
  20. private int timeout;
  21. @Value("${spring.redis.pool.max-idle}")
  22. private int maxIdle;
  23. @Value("${spring.redis.pool.min-idle}")
  24. private int minIdle;
  25. @Value("${spring.redis.pool.max-active}")
  26. private int maxActive;
  27. @Value("${spring.redis.pool.max-wait}")
  28. private long maxWait;
  29. private JedisConnectionFactory jedisConnectionFactory() {
  30. return new JedisConnectionFactory(redisStandaloneConfiguration(), clientConfiguration());
  31. }
  32. private RedisStandaloneConfiguration redisStandaloneConfiguration() {
  33. RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);
  34. redisStandaloneConfiguration.setDatabase(database);
  35. return redisStandaloneConfiguration;
  36. }
  37. private JedisPoolConfig poolConfig() {
  38. JedisPoolConfig config = new JedisPoolConfig();
  39. config.setMaxIdle(maxIdle);
  40. config.setMinIdle(minIdle);
  41. config.setMaxTotal(maxActive);
  42. config.setMaxWaitMillis(maxWait);
  43. return config;
  44. }
  45. private JedisClientConfiguration clientConfiguration() {
  46. JedisClientConfiguration jedisClientConfiguration = JedisClientConfiguration.builder()
  47. .usePooling()
  48. .poolConfig(poolConfig())
  49. .build();
  50. return jedisClientConfiguration;
  51. }
  52. @Bean
  53. public RedisTemplate<String, Object> redisTemplate() {
  54. RedisTemplate<String, Object> template = new RedisTemplate<>();
  55. template.setConnectionFactory(jedisConnectionFactory());
  56. template.setKeySerializer(new StringRedisSerializer());
  57. template.setHashKeySerializer(new StringRedisSerializer());
  58. template.setHashValueSerializer(new StringRedisSerializer());
  59. template.setValueSerializer(new StringRedisSerializer());
  60. return template;
  61. }
  62. }

4.创建测试类RedisConfigTest.java

  1. package com.szcatic.test;
  2. import java.util.List;
  3. import org.junit.jupiter.api.Test;
  4. import org.junit.jupiter.api.extension.ExtendWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.test.context.SpringBootTest;
  7. import org.springframework.context.annotation.Configuration;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.test.context.junit.jupiter.SpringExtension;
  10. import com.szcatic.Application;
  11. @Configuration
  12. @ExtendWith(SpringExtension.class)
  13. @SpringBootTest(classes = Application.class)
  14. public class RedisConfigTest {
  15. @Autowired
  16. RedisTemplate<String, Object> redisTemplate;
  17. @Test
  18. void testOpsForHash() {
  19. redisTemplate.opsForHash().put("hashValue","map1","map1-1");
  20. redisTemplate.opsForHash().put("hashValue","map2","map2-2");
  21. List<Object> hashList = redisTemplate.opsForHash().values("hashValue");
  22. System.out.println("hashList======" + hashList);
  23. }
  24. }

5.启动redis单机服务,执行测试方法testOpsForHash,控制台输出结果如下

  1. 14:31:20.919 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
  2. 14:31:20.940 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
  3. 14:31:20.964 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.szcatic.test.RedisConfigTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
  4. 14:31:20.975 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.szcatic.test.RedisConfigTest], using SpringBootContextLoader
  5. 14:31:20.990 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.szcatic.test.RedisConfigTest]: class path resource [com/szcatic/test/RedisConfigTest-context.xml] does not exist
  6. 14:31:20.990 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.szcatic.test.RedisConfigTest]: class path resource [com/szcatic/test/RedisConfigTestContext.groovy] does not exist
  7. 14:31:20.990 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.szcatic.test.RedisConfigTest]: no resource found for suffixes {-context.xml, Context.groovy}.
  8. 14:31:21.047 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.szcatic.test.RedisConfigTest]
  9. 14:31:21.164 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.szcatic.test.RedisConfigTest]: using defaults.
  10. 14:31:21.165 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
  11. 14:31:21.193 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@60015ef5, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@2f54a33d, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@1018bde2, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@65b3f4a4, org.springframework.test.context.support.DirtiesContextTestExecutionListener@f2ff811, org.springframework.test.context.transaction.TransactionalTestExecutionListener@568ff82, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@50caa560, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@2a266d09, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@5ab9e72c, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@186f8716, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@1d8bd0de, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@45ca843]
  12. 14:31:21.197 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@87a85e1 testClass = RedisConfigTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@671a5887 testClass = RedisConfigTest, locations = '{}', classes = '{class com.szcatic.Application, class com.szcatic.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@7692d9cc, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@43ee72e6, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@79efed2d, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@3c9d0b9d], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map['org.springframework.test.context.web.ServletTestExecutionListener.activateListener' -> true]], class annotated with @DirtiesContext [false] with mode [null].
  13. 14:31:21.225 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}
  14. . ____ _ __ _ _
  15. /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
  16. ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
  17. \\/ ___)| |_)| | | | | || (_| | ) ) ) )
  18. ' |____| .__|_| |_|_| |_\__, | / / / /
  19. =========|_|==============|___/=/_/_/_/
  20. :: Spring Boot :: (v2.1.0.RELEASE)
  21. 2018-11-22 14:31:21.625 INFO 12244 --- [ main] com.szcatic.test.RedisConfigTest : Starting RedisConfigTest on zsx with PID 12244 (started by admin in F:\workspace4.7\springboot)
  22. 2018-11-22 14:31:21.627 INFO 12244 --- [ main] com.szcatic.test.RedisConfigTest : No active profile set, falling back to default profiles: default
  23. 2018-11-22 14:31:23.549 INFO 12244 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Multiple Spring Data modules found, entering strict repository configuration mode!
  24. 2018-11-22 14:31:23.568 INFO 12244 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
  25. 2018-11-22 14:31:23.650 INFO 12244 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 40ms. Found 0 repository interfaces.
  26. 2018-11-22 14:31:24.312 INFO 12244 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$efc69acd] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
  27. 2018-11-22 14:31:26.464 INFO 12244 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
  28. 2018-11-22 14:31:28.324 INFO 12244 --- [ main] com.szcatic.test.RedisConfigTest : Started RedisConfigTest in 7.089 seconds (JVM running for 8.248)
  29. hashList======[map1-1, map2-2]
  30. 2018-11-22 14:31:29.494 INFO 12244 --- [ Thread-3] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzeDE4MjczMTE3MDAz_size_16_color_FFFFFF_t_70 从以上结果可以看出,操作redis数据库成功

6.项目目录结构

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3pzeDE4MjczMTE3MDAz_size_16_color_FFFFFF_t_70 1

发表评论

表情:
评论列表 (有 0 条评论,406人围观)

还没有评论,来说两句吧...

相关阅读