About Redis cluster construction, you can refer to my other article Redis cluster construction and simple use
What is Redis and what can it do
Redis is an open source (BSD license), memory-stored data structure server that can be used as a database , cache and message queue broker. It supports strings, hash tables, lists, sets, ordered sets, bitmaps, hyperloglogs and other data types. Built-in replication, Lua scripts, LRU eviction, transactions and different levels of disk persistence functions, while providing high availability through Redis Sentinel and automatic partitioning through Redis Cluster. (Excerpted from Redis official website)
As an in-memory database, in modern Internet web systems, Redis is still mainly used as a cache. Large-scale Internet Web systems have high performance requirements, and adding data caching between the front end and the data layer has become one of the essential means. The two most popular technologies currently are Redis and Memcached. As for the difference between the two, That’s not what this article is about. This article mainly talks about how Java web operates Redis and Redis cluster.
General Java programs operate Redis
Redis provides clients in multiple languages, the most popular one in Java is Jedis. Visit to view the source code and how to use it. Currently the latest version of Jedis is 2.9.0. Whether it is a stand-alone machine or a cluster, Jedis has very detailed instructions and example codes. Here is only a brief explanation. If you use Maven for package management, you need to reference the jedis package. This example uses the latest 2.9.0 version, as follows:
redis.clients jedis 2.9.0
Operation Redis stand-alone
import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; /** * Created by fengdezitai on 2016/10/9. */ public class JedisClient { private static final String host= "192.168.31.121"; private static final JedisClient jedisClient = new JedisClient(); private Jedis jedis = null; /** * 私有构造函数 */ private JedisClient(){} public static JedisClient getInstance(){ return jedisClient; } private JedisPoolConfig getPoolConfig(){ JedisPoolConfig jedisPoolConfig = new JedisPoolConfig(); jedisPoolConfig.setMaxIdle(10); jedisPoolConfig.setMaxTotal(100); jedisPoolConfig.setMaxWaitMillis(3000); return jedisPoolConfig; } /** * 添加 * @param key * @param value * @return * @throws Exception */ public Boolean add(String key,String value) throws Exception{ JedisPool pool = new JedisPool(getPoolConfig(),host); Jedis jedis = null; try { jedis = pool.getResource(); if(jedis.exists(key)){ throw new Exception(String.format("key (%s) 已存在 ",key)); } jedis.set(key,value); }catch (Exception e){ throw e; } finally { if(jedis!=null){ jedis.close(); } } pool.destroy(); return true; } /** * 获取值 * @param key * @return * @throws Exception */ public String get(String key) throws Exception{ JedisPool pool = new JedisPool(getPoolConfig(),host); Jedis jedis = null; String result = ""; try { jedis = pool.getResource(); result = jedis.get(key); }catch (Exception e){ throw e; } finally { if(jedis!=null){ jedis.close(); } } pool.destroy(); return result; } public static void main(String[] args) { JedisClient jedisClient = JedisClient.getInstance(); try { /*Boolean result = jedisClient.add("hello", "redis1"); if(result){ System.out.println("success"); }*/ System.out.println(jedisClient.get("hello")); }catch (Exception e){ e.printStackTrace(); } } }
Operation redis cluster
import redis.clients.jedis.*; import java.util.HashSet; import java.util.Set; /** * Created by fengdezitai on 2016/10/13. */ public class JedisClusterClient { private static int count = 0; private static final JedisClusterClient redisClusterClient = new JedisClusterClient(); /** * 私有构造函数 */ private JedisClusterClient() {} public static JedisClusterClient getInstance() { return redisClusterClient; } private JedisPoolConfig getPoolConfig(){ JedisPoolConfig config = new JedisPoolConfig(); config.setMaxTotal(1000); config.setMaxIdle(100); config.setTestOnBorrow(true); return config; } public void SaveRedisCluster() { Set jedisClusterNodes = new HashSet(); jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7000)); jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7001)); jedisClusterNodes.add(new HostAndPort("192.168.31.245", 7002)); jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7003)); jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7004)); jedisClusterNodes.add(new HostAndPort("192.168.31.210", 7005)); JedisCluster jc = new JedisCluster(jedisClusterNodes,getPoolConfig()); jc.set("cluster", "this is a redis cluster"); String result = jc.get("cluster"); System.out.println(result); } public static void main(String[] args) { JedisClusterClient jedisClusterClient = JedisClusterClient.getInstance(); jedisClusterClient.SaveRedisCluster(); } }
Spring mvc operation Redis
Operation in Spring mvc Redis, of course, we must first set up the Spring mvc framework. The following is assuming that the Spring mvc environment has been set up. In this example, the Spring version is 4.3.2 RELEASE. The maven reference about Spring is as follows:
4.3.2.RELEASE org.springframework spring-core ${spring.version} commons-logging commons-logging org.springframework spring-web ${spring.version} org.springframework spring-oxm ${spring.version} org.springframework spring-tx ${spring.version} org.springframework spring-jdbc ${spring.version} org.springframework spring-webmvc ${spring.version} commons-logging commons-logging org.springframework spring-aop ${spring.version} org.springframework spring-context-support ${spring.version} org.springframework spring-test ${spring.version}
Operate Redis stand-alone
Only use Jedis to implement the injection (different from the reference below spring-data-redis)
Just take the previous JedisClient code and quote it, you only need to implement one Accessing the Redis Service can be integrated into Spring mvc. The Service code is as follows:
import org.springframework.stereotype.Service; import util.JedisClient; /** * Created by fengdezitai on 2016/10/9. */ @Service public class RedisService { public String get(String key) throws Exception{ JedisClient jedisClient = JedisClient.getInstance(); //上面实现的JedisClient String result = ""; try { result = jedisClient.get("hello"); }catch (Exception e){ throw e; } return result; } }
Controller is implemented as follows:
@Controller @RequestMapping(value = "redisAllInOne") public class RedisAllInOneController { @Autowired private RedisService redisService; @RequestMapping(value = "get",method = RequestMethod.GET) @ResponseBody public Object getByMyService(String key){ try { String result = redisService.get(key); return result; }catch (Exception e){ e.printStackTrace(); } return null; } }
Use the spring-data-redis package for integration
The above is the injection implemented by myself. Here, spring-data-redis is used for integration. It only requires simple configuration. You need The reference to the maven package is as follows, the version is the latest version 1.7.2.RELEASE:
org.springframework.data spring-data-redis 1.7.2.RELEASE
Using spring-data-redis eliminates the need to implement the injection process by yourself. Through some of the configurations it provides, you can achieve connection pool configuration, RedisTemplate configuration, JedisConnectionFactory configuration; through JedisConnectionFactory, you can configure the connection pool parameters, redis server, port, password, timeout, database index, etc.; RedisTemplate is the injected bean, and you can use the entities automatically injected by RedisTemplate to perform a series of redis operations. For details, see Configuration;
redis service attribute configuration file:
redis.maxIdle=300 redis.maxWait=3000 redis.testOnBorrow=true redis.host=192.168.31.121 redis.port=6379 redis.password=password redis.timeout=3000
spring-data-redis xml configuration file redis-context.xml:
--> -->
Then quote the above file in the spring configuration file:
Explain the above configuration:
poolConfig configures the redis connection pool, and then configures two JedisConnectionFactory and RedisTemplate. One RedisTemplate corresponds to one JedisConnectionFactory. In this way, different Redis connections can be configured according to the scenario, such as inconsistent timeout requirements, database 0-15 can store different data, etc. . Database 1 and 2 are configured here. Calling commonRedisTemplate will save it to database1, and calling cacheRedisTemplate will save it to database2.
Afterwards, you can inject and reference these two RedisTemplates in the Service layer, as follows:
import org.apache.commons.lang3.StringUtils; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; import javax.annotation.Resource; import java.io.*; @Repository public class RedisCache { @Resource(name = "cacheRedisTemplate") private RedisTemplate
Finally call it in the Controller
@Autowired private RedisCache redisCache; @RequestMapping(value = "get", method = RequestMethod.GET) @ResponseBody public Object getByMyService(String key) { try { String result = redisService.get(key); return result; } catch (Exception e) { e.printStackTrace(); } return null; } @RequestMapping(value = "save", method = RequestMethod.GET) @ResponseBody public Object save() { Token token = new Token(); token.setAccess_token("token"); token.setExpires_in(1000); try { redisCache.put("token", token); } catch (Exception e) { e.printStackTrace(); } return "ok"; }
To operate the Redis cluster
Only use Jedis to implement the injection (different from the spring reference below) -data-redis)
Just take the previous JedisClusterClient code and reference it. You only need to implement a Service to access Redis, and it can be integrated into Spring mvc. The Service code is as follows:
import org.springframework.stereotype.Service; import util.JedisClusterClient; /** * Created by fengdezitai on 2016/10/13. */ @Service public class RedisClusterService { public void save() throws Exception{ //调用 JedisClusterClient 中的方法 JedisClusterClient jedisClusterClient = JedisClusterClient.getInstance(); try { jedisClusterClient.SaveRedisCluster(); }catch (Exception e){ throw e; } } }
Finally, call the implemented Service in the Controller
@Controller @RequestMapping(value = "redisCluster") public class RedisClusterController { @Autowired private RedisClusterService redisClusterService; @RequestMapping(value = "save",method = RequestMethod.GET) @ResponseBody public Object save(){ try{ redisClusterService.save(); }catch (Exception e){ e.printStackTrace(); return String.format("error: %s",e.getMessage()); } return "ok"; } }
Use the spring-data-redis package for integration
The Spring and spring-data-redis maven package references are the same as before. The reason why spring- data-redis 1.7.2.RELEASE, because currently only this latest version supports cluster operations.
redis cluster service attribute configuration
redis.maxIdle=300 redis.maxWait=3000 redis.testOnBorrow=false redis.timeout=3000
spring-data-redis xml cluster configuration file redis-cluster-context.xml
<br/>
will be later referenced in the Spring configuration file
<br/>
Explain the above configuration:
poolConfig is the connection pool configuration , redisClusterConfig configures each node of the Redis cluster (node host and port are best written in the attribute configuration file). The cluster construction can be found in my other blog. Then the following is the same as the stand-alone configuration, a pair of JedisConnectionFactory and RedisTemplate.
Afterwards, this RedisTemplate can be injected and referenced in the Service layer. The code is as follows:
import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Repository; import java.io.*; /** * Created by fengdezitai on 2016/9/29. */ @Repository public class RedisClusterCache { @Autowired private RedisTemplate clusterRedisTemplate; public void put(Object key, Object value) { if(null == value) { return; } if(value instanceof String) { if(StringUtils.isEmpty(value.toString())) { return; } } // TODO Auto-generated method stub final String keyf = key + ""; final Object valuef = value; final long liveTime = 86400; clusterRedisTemplate.execute(new RedisCallback
Finally, just call it in the Controller
@Controller @RequestMapping(value = "redisCluster") public class RedisClusterController { @Autowired private RedisClusterCache redisClusterCache; @RequestMapping(value = "clusterSave",method = {RequestMethod.GET,RequestMethod.POST}) @ResponseBody public Object clusterSave(){ //redisClusterCache.put("cluster","save cluster"); Token token = new Token(); token.setExpires_in(1000); token.setAccess_token("hello world"); redisClusterCache.put("token",token); return "ok"; } @RequestMapping(value = "getKey",method = RequestMethod.GET) @ResponseBody public Object getCluster(String key){ Object val = redisClusterCache.get(key); return val; } }
Notes:
Version issue, if you use spring-data-redis to integrate the Reids cluster, only the latest version 1.7 of spring-data-redis includes operations on the cluster, and some functions in the latest spring-data-redis are not suitable for Spring mvc There are also some restrictions on the version, so try to choose a higher version of Spring mvc.
If the stored value is an entity object, then the Serializable interface must be implemented
[Related recommendations]
1. Detailed explanation of usage code examples of Spring framework annotations
2. Spring and Java transaction management learning Detailed explanation of Hibernate code