Spring Bootを使ってインテグレーションする方法


今日、日月はここでspringBootをどうやって使うか教えます。実は比較的簡単です。ネットでも大柄の教程があります。まずネットの紹介を使います。
定義
REmote DIctionary ServerはSalvator Sanfilippoによって書かれたkey-valueストレージシステムです。
RedisはオープンソースのANSI C言語を使用してBSDプロトコルを作成し、ネットワークをサポートし、メモリに基づいても持続可能なログタイプ、Key-Valueデータベースを作成し、複数の言語のAPIを提供する。
値は文字列(String)、ハッシュ(Map)、リスト(list)、セット(sets)、および順序セット(sorted sets)などのタイプであることができるので、データ構造サーバと呼ばれることが多い。
reidsのメリット
以下はRedisのいくつかの利点です。
非常に速い-Redisは非常に速く、毎秒約110000回の設定(SET)動作が可能で、毎秒約81000回の読み取り/取得(GET)動作が可能です。
豊富なデータタイプをサポートします。Redisは、リスト、セット、並べ替えセット、ハッシュなど、開発者がよく使うデータの多くをサポートします。これはRedisを様々な問題を解決するために容易に利用できます。どのような問題がより良く使用できるかを知っています。
動作は原子的である。すべてのRedis動作は原子的な操作である。これは、二つのクライアントが同時にアクセスすれば、Redisサーバが更新された値を受信できることを保証する。
マルチユーティリティ-Redisは、キャッシュ、メッセージキュー(Redisローカルサポートリリース/購読)、アプリケーション内の任意の短期データ、例えば、ウェブアプリケーション内のセッション、ウェブアクセスカウントなどの様々な用例に使用されてもよい。
Redisインストール
Windowでインストール
ダウンロード先:https://github.com/MSOpenTech/redis/releases。
Redisは32ビットと64ビットをサポートします。これはあなたのシステムプラットフォームの実際の状況によって選択したいです。ここでRedis-x 64-xxx.zip圧縮パッケージをダウンロードして、解凍した後、フォルダをredisと名づけます。
cmdウィンドウを開いてcdコマンドでディレクトリをCに切り替えます。\redis
実行redis-server.exe redis.windows.conf便利になりたいなら、redisのパスをシステムの環境変数に加えることができます。これでもうパスを失うことができます。後のredis.windows.com fは省略できます。省略すれば、デフォルトが有効になります。入力後、次の画面が表示されます。
在这里插入图片描述
インテグレーション
私たちは前の章のプロジェクトを延長しました。Springboot統合springcloud-configでdataSourceの熱的展開を実現です。
1、依存を追加する

<!--  redis-->
<dependency>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-redis</artifactId>
 <version>1.4.1.RELEASE</version>
</dependency>
<dependency>
 <groupId>com.alibaba</groupId>
 <artifactId>fastjson</artifactId>
 <version>1.2.3</version>
</dependency>
<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
</dependency>
2、配置センターにredis配置を追加する

spring.redis.host=127.0.0.1
#Redis       
spring.redis.port=6379
#Redis       (    )
spring.redis.password=
#        (          )
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=30000
3、配置類RedisConfig

import java.lang.reflect.Method;
import org.springframework.beans.factory.annotation.Value;
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.cloud.context.config.annotation.RefreshScope;
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.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import com.fasterxml.jackson.annotation.PropertyAccessor; 
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.databind.ObjectMapper;
@Configuration
@EnableCaching
@RefreshScope
public class RedisConfig extends CachingConfigurerSupport{
 @Value("${spring.redis.host}")
 private String host;
 @Value("${spring.redis.port}")
 private int port;
 @Value("${spring.redis.timeout}")
 private int timeout;
 @Value("${spring.redis.password}")
 private String password;
 @Value("${spring.redis.pool.max-active}")
 private int maxActive;
 @Value("${spring.redis.pool.max-wait}")
 private int maxWait;
 @Value("${spring.redis.pool.max-idle}")
 private int maxIdle;
 @Value("${spring.redis.pool.min-idle}")
 private int minIdle;
 
 @RefreshScope
 @Bean
 public KeyGenerator wiselyKeyGenerator(){
 return new KeyGenerator() {
 @Override
 public Object generate(Object target, Method method, Object... params) {
 StringBuilder sb = new StringBuilder();
 sb.append(target.getClass().getName());
 sb.append(method.getName());
 for (Object obj : params) {
  sb.append(obj.toString());
 }
 return sb.toString();
 }
 };
 }
 
 @RefreshScope
 @Bean
 public JedisConnectionFactory redisConnectionFactory() {
 JedisConnectionFactory factory = new JedisConnectionFactory();
 factory.setHostName(host);
 factory.setPort(port);
 factory.setTimeout(timeout); //        
 factory.setPassword(password);
 factory.getPoolConfig().setMaxIdle(maxIdle);
 factory.getPoolConfig().setMinIdle(minIdle);
 factory.getPoolConfig().setMaxTotal(maxActive);
 factory.getPoolConfig().setMaxWaitMillis(maxWait);
 return factory;
 }
 
 @RefreshScope
 @Bean
 public CacheManager cacheManager(RedisTemplate redisTemplate) {
 RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
 // Number of seconds before expiration. Defaults to unlimited (0)
 cacheManager.setDefaultExpiration(10); //  key-value    
 return cacheManager;
 }
 
 @RefreshScope
 @Bean
 public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
 StringRedisTemplate template = new StringRedisTemplate(factory);
 setSerializer(template); //       ,  ReportBean     Serializable  
 template.afterPropertiesSet();
 return template;
 }
 
 @RefreshScope
 private void setSerializer(StringRedisTemplate template) {
 Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
 ObjectMapper om = new ObjectMapper();
 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
 om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
 jackson2JsonRedisSerializer.setObjectMapper(om);
 template.setValueSerializer(jackson2JsonRedisSerializer);
 }
}
4、RedisUtils類

import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisUtils {
 @Autowired
 private RedisTemplate redisTemplate;
 /**
 *     
 * @param key
 * @param value
 * @return
 */
 public boolean set(final String key, Object value) {
 boolean result = false;
 try {
 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
 operations.set(key, value);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 /**
 *           
 * @param key
 * @param value
 * @return
 */
 public boolean set(final String key, Object value, Long expireTime ,TimeUnit timeUnit) {
 boolean result = false;
 try {
 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
 operations.set(key, value);
 redisTemplate.expire(key, expireTime, timeUnit);
 result = true;
 } catch (Exception e) {
 e.printStackTrace();
 }
 return result;
 }
 /**
 *        value
 * @param keys
 */
 public void remove(final String... keys) {
 for (String key : keys) {
 remove(key);
 }
 }
 /**
 *     key
 * @param pattern
 */
 public void removePattern(final String pattern) {
 Set<Serializable> keys = redisTemplate.keys(pattern);
 if (keys.size() > 0){
 redisTemplate.delete(keys);
 }
 }
 /**
 *      value
 * @param key
 */
 public void remove(final String key) {
 if (exists(key)) {
 redisTemplate.delete(key);
 }
 }
 /**
 *            value
 * @param key
 * @return
 */
 public boolean exists(final String key) {
 return redisTemplate.hasKey(key);
 }
 /**
 *     
 * @param key
 * @return
 */
 public Object get(final String key) {
 Object result = null;
 ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
 result = operations.get(key);
 return result;
 }
 /**
 *      
 * @param key
 * @param hashKey
 * @param value
 */
 public void hmSet(String key, Object hashKey, Object value){
 HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
 hash.put(key,hashKey,value);
 }
 /**
 *       
 * @param key
 * @param hashKey
 * @return
 */
 public Object hmGet(String key, Object hashKey){
 HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
 return hash.get(key,hashKey);
 }
 /**
 *     
 * @param k
 * @param v
 */
 public void lPush(String k,Object v){
 ListOperations<String, Object> list = redisTemplate.opsForList();
 list.rightPush(k,v);
 }
 /**
 *     
 * @param k
 * @param l
 * @param l1
 * @return
 */
 public List<Object> lRange(String k, long l, long l1){
 ListOperations<String, Object> list = redisTemplate.opsForList();
 return list.range(k,l,l1);
 }
 /**
 *     
 * @param key
 * @param value
 */
 public void add(String key,Object value){
 SetOperations<String, Object> set = redisTemplate.opsForSet();
 set.add(key,value);
 }
 /**
 *     
 * @param key
 * @return
 */
 public Set<Object> setMembers(String key){
 SetOperations<String, Object> set = redisTemplate.opsForSet();
 return set.members(key);
 }
 /**
 *       
 * @param key
 * @param value
 * @param scoure
 */
 public void zAdd(String key,Object value,double scoure){
 ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
 zset.add(key,value,scoure);
 }
 /**
 *       
 * @param key
 * @param scoure
 * @param scoure1
 * @return
 */
 public Set<Object> rangeByScore(String key,double scoure,double scoure1){
 ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
 return zset.rangeByScore(key, scoure, scoure1);
 }
5、テスト、controllerを修正する

import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.chenqi.springboot.redis.RedisUtils;
import com.chenqi.springboot.service.TestService;
@RestController
public class SpringBootController {
 
 public static final Logger log = LoggerFactory.getLogger(SpringBootController.class);
 
 @Autowired
 TestService testService;
 
 @Autowired
 private RedisUtils redisUtils;
 @RequestMapping(value = "/hello/{id}")
 public String hello(@PathVariable(value = "id") String id){
 //         
 boolean hasKey = redisUtils.exists(id);
 String str = "";
 if(hasKey){
 //    
 Object object = redisUtils.get(id);
 log.info("        "+ object);
 str = object.toString();
 }else{
 //         
 log.info("         ");
 str = testService.test();
 //      (set      :key ,user  ,      10(long  ),    )
 redisUtils.set(id,str,10L,TimeUnit.MINUTES);
 log.info("      " + str);
 }
 return str;
 }
}
プロジェクトを開始し、初めての訪問:http://localhost:8002/hello/111
在这里插入图片描述
在这里插入图片描述
コンソール出力によって、データベースから取得したデータが見えます。そして、redisキャッシュに保存されました。
ブラウザを再更新します。
在这里插入图片描述
2回目はキャッシュから読み取ったので、ブラウザを更新してみます。
在这里插入图片描述
後はキャッシュから取得されます。
これで私たちのredisを配置します。
Spring Boot統合Redis-demoダウンロード
demoが必要な兄弟は自分でダウンロードしてください。緊急ではないので、メッセージメールは普通48時間以内に送ります。
ここで、SpringBootを使った集成redisの方法についての記事を紹介します。SpringBootの集成redisの内容については、以前の文章を検索したり、以下の関連記事を見たりしてください。これからもよろしくお願いします。