Spring Boot (9) Redis (Connect, delete, change, cluster, use with session)

Source: Internet
Author: User
Tags assert serialization redis cluster redis server

1. Establish a connection

1.1 Pom.xml

<!--Redis-related support-        <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 Database index (default is 0) spring.redis.database=0# Redis server address spring.redis.host=192.168.88.134# Redis Server connection Port spring.redis.port=6379# Redis Server connection password (default is empty) spring.redis.password=123456# connection pool Maximum number of connections (using negative values means there is no limit) spring.redis.pool.max-active=8# Connection pool Maximum blocking wait time (with negative values for no limit) spring.redis.pool.max-wait=-1# maximum idle connections in the connection pool spring.redis.pool.max-idle=8# Minimum idle connection in connection pool spring.redis.pool.min-idle=0# connection time-out (ms) 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 Running the test

2, to the operation of the Redis to change the additions and deletions

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 Logg    ER logger = loggerfactory.getlogger (This.getclass ());    @Autowired private Citymapper Citymapper;    @Autowired private Redistemplate redistemplate;    Private final String Key_prefix = "City_"; /** * Get City Logic: * If the cache exists, get city information from the cache * If the cache does not exist, obtain city information from the DB, and then insert the cache */@Override public Cities findonecity (Integer ID)        {valueoperations<string, city> valueoperations = Redistemplate.opsforvalue (); The cache has a String key= Key_prefix + ID;        Boolean haskey = Redistemplate.haskey (key);            if (Haskey) {City city = Valueoperations.get (key);            Logger.info ("cityserviceimpl.findonecity (): Get City >> from cache" + city.tostring ());        return city;        }//Get data from MySQL database city city = Citymapper.selectbyprimarykey (ID);        into the cache.        Valueoperations.set (Key, City, ten, timeunit.seconds);        Logger.info ("Cityserviceimpl.findonecity (): City added Cache >>" + city.tostring ());    return city;    } @Override public int savecity {return citymapper.insert (city); } @Override public int modifycity (city city) {//Update data in db int count = Citymapper.updatebyprimarykey (CI        TY);        If it exists in the cache, remove it.        String key = Key_prefix + City.getid ();        Boolean haskey = Redistemplate.haskey (key);            if (Haskey) {redistemplate.delete (key); Logger.info ("cityserviceimpl.modifycity removed City from cache"+ city.tostring ());    } return count; } @Override public int deletecity (Integer ID) {//delete data in db int count = Citymapper.deletebyprimarykey (i        D);        If it exists in the cache, remove it.        String key = Key_prefix + ID;        Boolean haskey = Redistemplate.haskey (key);            if (Haskey) {redistemplate.delete (key);        Logger.info ("cityserviceimpl.modifycity removed the city ID from the cache:" + ID);    } return count; }}

3. If the cluster

Pom.xml

<!--Redis-related support, which by default includes Jedis dependencies--        <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

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; /** * Note: When we use redistemplate, when we do not specify &LT;K, v> specific values, * spring defaults to Defaultserializer = new Jdkserializationredisseri     Alizer (); To serialize the Key,value, * so this time Redis can come out a bunch of \xac\xed\x00\x05t\x00\tb this stuff;     ** So we can choose two methods of processing: * 1. Use redistemplate<string,string> to specify directly.     * 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 (Connect, delete, change, cluster, use with session)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.