春ブーツ2 Redisの統合

Redisのタイプ、キー値のデータベースをログに記録することができ、メモリの持続性に基づいてANSI C、サポートネットワークで書かれたオープンソースの使用であり、多言語APIを提供します。
Redisのキー値記憶システム、ストリング(文字列)、リスト(リスト)、SET(セット)、ZSET(ソートセット-順序付けられた集合)サポート格納された値の型であり、ハッシュ(ハッシュタイプ)。

、のpom.xmlモジュールに組み込まのRedis

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

二つには、コンフィギュレーションをapplication.properties

server.port = 9001

# Redis数据库索引(默认为0)
spring.redis.database = 0
# Redis服务器地址
spring.redis.host = 127.0.0.1
# Redis服务器连接端口
spring.redis.port = 6379
# Redis服务器连接密码(如果没有则设置为空)
spring.redis.password = 123456
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active = 8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait = -1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle = 8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle = 0
# 连接超时时间(毫秒)
spring.redis.timeout = 1000

注:
オンラインいくつかの例を0に設定することはできません、初めはコピーされ、0に設定spring.redis.timeout、結果は接続タイムアウトエラー報告
のRedisに接続できませんが、ネストされた例外は io.lettuce.core.RedisCommandTimeoutExceptionです:コマンドの時限アウト

三、RedisConfig設定

します。https://blog.csdn.net/lx1309244704/article/details/80696235からコード

package com.example.demo.config;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping;

@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {

	@Resource
	private LettuceConnectionFactory lettuceConnectionFactory;

	@Bean
	public KeyGenerator keyGenerator() {
		return new KeyGenerator() {
			@Override
			public Object generate(Object target, Method method, Object... params) {
				StringBuffer sb = new StringBuffer();
				sb.append(target.getClass().getName());
				sb.append(method.getName());
				for (Object obj : params) {
					sb.append(obj.toString());
				}
				return sb.toString();
			}
		};
	}

	// 缓存管理器
	@Bean
	public CacheManager cacheManager() {
		RedisCacheManager.RedisCacheManagerBuilder builder = 

RedisCacheManager.RedisCacheManagerBuilder.fromConnectionFactory(lettuceConnectionFactory);
		@SuppressWarnings("serial")
		Set<String> cacheNames = new HashSet<String>() {
			{
				add("codeNameCache");
			}
		};
		builder.initialCacheNames(cacheNames);
		return builder.build();
	}

	/**
	 * RedisTemplate配置
	 */
	@Bean
	public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
		// 设置序列化
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new 

Jackson2JsonRedisSerializer<Object>(Object.class);
		ObjectMapper om = new ObjectMapper();
		om.setVisibility(PropertyAccessor.ALL, Visibility.ANY);
		om.enableDefaultTyping(DefaultTyping.NON_FINAL);
		jackson2JsonRedisSerializer.setObjectMapper(om);
		// 配置redisTemplate
		RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
		redisTemplate.setConnectionFactory(lettuceConnectionFactory);
		RedisSerializer<?> stringSerializer = new StringRedisSerializer();
		redisTemplate.setKeySerializer(stringSerializer);// key序列化
		redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);// value序列化
		redisTemplate.setHashKeySerializer(stringSerializer);// Hash key序列化
		redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);// Hash value序列化
		redisTemplate.afterPropertiesSet();
		return redisTemplate;
	}

}

四、Redisの使用例

package com.example.demo.web.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class DemoController {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@RequestMapping(value = "/redis", method = RequestMethod.GET)
	public String redis() {
		
		stringRedisTemplate.opsForValue().set("test1", "test11111");//存入数据
		String test1 = stringRedisTemplate.opsForValue().get("test1");
				
		return test1;
	}	
		 
}

 ブラウザでhttp:// localhostを:test11111:9001 / Redisの、あなたは出力され見ることができます

注:RedisTemplateデータ構造は、5つの操作を定義します

redisTemplate.opsForValue();  //操作字符串
redisTemplate.opsForHash();   //操作hash
redisTemplate.opsForList();   //操作list
redisTemplate.opsForSet();    //操作set
redisTemplate.opsForZSet();   //操作有序set

第五に、ユニットテスト

package com.example.demo;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Test
	public void contextLoads() {
	}
	
	@Test
    public void test1() throws Exception {
        stringRedisTemplate.opsForValue().set("a", "123");
        Assert.assertEquals("123", stringRedisTemplate.opsForValue().get("a"));
    }
		
	
}

 

おすすめ

転載: blog.csdn.net/gdjlc/article/details/84623055