spring boot(9) redis(串連,增刪改查,叢集,和session一起使用)

來源:互聯網
上載者:User

標籤:技術   framework   com   建立   檔案   取資料   find   ann   assert   

1.建立串連

1.1 pom.xml

 <!-- redis 相關支援 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-redis</artifactId>            <version>1.3.2.RELEASE</version>        </dependency>

1.2 application.properties

#Servlet連接埠號碼server.port=8088# REDIS (RedisProperties)# Redis資料庫索引(預設為0)spring.redis.database=0# Redis伺服器位址spring.redis.host=192.168.88.134# 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=0

1.3 StringRedisTemplateTest.java

package com.guilf.servlet;import org.junit.Test;import org.junit.runner.RunWith;import org.slf4j.Logger;import org.slf4j.LoggerFactory;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.SpringJUnit4ClassRunner;/** * Created by hong on 2017/5/2. */@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTestpublic class StringRedisTemplateTest {    private final Logger logger = LoggerFactory.getLogger(this.getClass());    @Autowired    private StringRedisTemplate stringRedisTemplate;    @Test    public  void test(){        stringRedisTemplate.opsForValue().set("aaa","aaa111");        logger.info(stringRedisTemplate.opsForValue().get("aaa"));    }}

  1.4 運行測試

2,對增刪改查 redis的操作

package com.hong.service.impl;import com.hong.domain.City;import com.hong.mapper.CityMapper;import com.hong.service.CityService;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Service;import java.util.concurrent.TimeUnit;/** *  */@Servicepublic class CityServiceImpl implements CityService {    private final Logger logger = LoggerFactory.getLogger(this.getClass());    @Autowired    private CityMapper cityMapper;    @Autowired    private RedisTemplate redisTemplate;    private final String KEY_PREFIX = "city_";    /**     * 擷取城市邏輯:     * 如果緩衝存在,從緩衝中擷取城市資訊     * 如果緩衝不存在,從 DB 中擷取城市資訊,然後插入緩衝     */    @Override    public City findOneCity(Integer id) {        ValueOperations<String, City> valueOperations = redisTemplate.opsForValue();        //緩衝存在        String key = KEY_PREFIX + id;        boolean hasKey = redisTemplate.hasKey(key);        if (hasKey) {            City city = valueOperations.get(key);            logger.info("CityServiceImpl.findOneCity() : 從緩衝中擷取了城市 >> " + city.toString());            return city;        }        //從mysql 資料庫中擷取資料        City city = cityMapper.selectByPrimaryKey(id);        //存入緩衝中.        valueOperations.set(key, city, 10, TimeUnit.SECONDS);        logger.info("CityServiceImpl.findOneCity() : 城市加入了緩衝 >> " + city.toString());        return city;    }    @Override    public int saveCity(City city) {        return cityMapper.insert(city);    }    @Override    public int modifyCity(City city) {        //更新DB中的資料        int count = cityMapper.updateByPrimaryKey(city);        //如果緩衝中存在,移除。        String key = KEY_PREFIX + city.getId();        boolean hasKey = redisTemplate.hasKey(key);        if (hasKey) {            redisTemplate.delete(key);            logger.info("CityServiceImpl.modifyCity 從緩衝中移除了城市" + city.toString());        }        return count;    }    @Override    public int deleteCity(Integer id) {        //刪除DB中的資料        int count = cityMapper.deleteByPrimaryKey(id);        //如果緩衝中存在,移除。        String key = KEY_PREFIX + id;        boolean hasKey = redisTemplate.hasKey(key);        if (hasKey) {            redisTemplate.delete(key);            logger.info("CityServiceImpl.modifyCity 從緩衝中移除了城市 ID:" + id);        }        return count;    }}

 

3.如果是叢集

pom.xml

 <!-- redis 相關支援, 預設包含了Jedis依賴 -->        <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-redis</artifactId>            <version>1.3.2.RELEASE</version>        </dependency>

application.properties

#redis clusterspring.redis.cluster.nodes=127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002spring.redis.cluster.commandTimeout=5000

  

RedisProperties.java

package com.guilf.config;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/** *  */@Component@ConfigurationProperties(prefix = "spring.redis.cluster")public class RedisProperties {    private String nodes;    private Integer   commandTimeout;    public String getNodes() {        return nodes;    }    public void setNodes(String nodes) {        this.nodes = nodes;    }    public Integer getCommandTimeout() {        return commandTimeout;    }    public void setCommandTimeout(Integer commandTimeout) {        this.commandTimeout = commandTimeout;    }}

  JedisClusterConfig.java

package com.guilf.config;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.core.env.MapPropertySource;import org.springframework.data.redis.connection.RedisClusterConfiguration;import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.StringRedisSerializer;import redis.clients.jedis.HostAndPort;import redis.clients.jedis.JedisCluster;import java.util.HashMap;import java.util.HashSet;import java.util.Map;import java.util.Set;/** * */@Configuration@ConditionalOnClass({JedisCluster.class})@EnableConfigurationProperties(RedisProperties.class)public class JedisClusterConfig {    @Autowired    private RedisProperties redisProperties;    @Bean    public JedisCluster jedisClusterFactory() {        String[] serverArray = redisProperties.getNodes().split(",");        Set<HostAndPort> nodes = new HashSet<>();        for (String ipPort: serverArray) {            String[] ipPortPair = ipPort.split(":");            nodes.add(new HostAndPort(ipPortPair[0].trim(),Integer.valueOf(ipPortPair[1].trim())));        }        return new JedisCluster(nodes, redisProperties.getCommandTimeout());    }    @Bean    public RedisTemplate redisTemplateFactory(){        RedisTemplate redisTemplate =new RedisTemplate();        redisTemplate.setConnectionFactory(jedisConnectionFactory());        //指定具體序列化方式  不過這種方式不是很好,一個系統中可能對應值的類型不一樣,如果全部使用StringRedisSerializer 序列化        //會照成其他類型報錯,所以還是推薦使用第一種,直接指定泛型的類型,spring 會根據指定類型序列化。        //redisTemplate.setKeySerializer( new StringRedisSerializer());        //redisTemplate.setValueSerializer(new StringRedisSerializer());        //redisTemplate.setHashKeySerializer(new StringRedisSerializer());        //redisTemplate.setHashValueSerializer(new StringRedisSerializer());        return redisTemplate;    }    /**     * redisCluster配置     * @return     */    @Bean    public RedisClusterConfiguration redisClusterConfiguration() {        Map<String, Object> source = new HashMap<String, Object>();        source.put("spring.redis.cluster.nodes", redisProperties.getNodes());        source.put("spring.redis.cluster.timeout", redisProperties.getCommandTimeout());        return new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));    }    /**     * 其實在JedisConnectionFactory的afterPropertiesSet()方法 中     * if(cluster !=null) this.cluster =createCluster();     * 也就是當     * spring.redis.cluster.nodes 配置好的情況下,就可以執行個體化 JedisCluster.     * 也就是說,我們使用JedisCluster 的方式只需要在application.properties 設定檔中     *     * #redis cluster     *  spring.redis.cluster.nodes=127.0.0.1:7000,127.0.0.1:7001,127.0.0.1:7002     *     * RedisTemplate.afterPropertiesSet() 中查看到最終方法中使用了JedisCluster 對象。     * 也就是說 redisTemplate依賴jedis ,內部操作的就是jedis,同理內部也操作jedisCluster.     *     *     * @return     */    @Bean    public JedisConnectionFactory jedisConnectionFactory() {        return new JedisConnectionFactory(redisClusterConfiguration());    }}

  TestRedisCluster.java

package com.guilf;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import org.springframework.test.context.web.WebAppConfiguration;import redis.clients.jedis.JedisCluster;/** *  */@RunWith(SpringJUnit4ClassRunner.class)@SpringBootTest(classes ={Application.class})@WebAppConfigurationpublic class TestRedisCluster {    private final Logger logger = LoggerFactory.getLogger(this.getClass());    @Autowired    private JedisCluster jedisCluster;    /**     * 注: 我們在使用RedisTemplate 時,在不指定<K, V> 具體值時,     * spring預設採用defaultSerializer = new JdkSerializationRedisSerializer();來對key,value進行序列化操作,     * 所以這時候redis 的可以 就會出來一堆的\xac\xed\x00\x05t\x00\tb 這種東西;     *     * 所以我們可以選擇兩種處理方法:     * 1.直接使用RedisTemplate<String,String>  指定。     * 2.     *     */    @Autowired    private RedisTemplate<String,String> redisTemplate;    @Test    public void test(){        jedisCluster.set("test_jedis_cluster","123456");        Assert.assertEquals("123456",jedisCluster.get("test_jedis_cluster"));        String value = jedisCluster.get("test_jedis_cluster");        logger.info(value);        redisTemplate.opsForValue().set("kkk","kkk");        redisTemplate.opsForValue().set("k2","v2");        logger.info(redisTemplate.opsForValue().get("kkk"));        logger.info(redisTemplate.opsForValue().get("test_jedis_cluster"));    }}

  

4.

spring boot(9) redis(串連,增刪改查,叢集,和session一起使用)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.