Spring Data Redis cluster (Sentinel implementation) and simple spring memcached distributed initial use __spring

Source: Internet
Author: User
Tags aop failover memcached redis redis cluster redis server

I am a rookie, just graduated not long ago, in a company in Shanghai, the company has counted I have 3 Java programmers, the other two have two work experience, they are responsible for app interface development, I am a person responsible for the background management interface development, the company project Framework is built with spring, The development tools are also spring, the persistence layer integrates spring data jap and mybatis, the control layer is spring MVC, and for me just out of campus, I think this frame tower is a special cow. Due to the project's permissions to do a bit more complex, and query the place particularly much, the speed of the Web page loading is particularly slow, the boss said that the right to judge put me in the cache, let me do, I was stunned, I just came out from school, only know hibernate two level cache, Eldest brother let me choose one in memcached and Redis, also do cluster mode, I was still probation period, in order to highlight their ability to bite the bullet and promised to come down. Now write down the distance between the two caches that I am learning.


Redis Sentinel Introduction: (Here copy)

Redis's Sentinel system is used to manage multiple Redis servers (instance), which performs the following three tasks: monitoring (monitoring): Sentinel will constantly check your home server and from the server for proper operation. Reminder (Notification): When a problem occurs on a Redis server that is being monitored, Sentinel can send notifications to administrators or other applications via the API. automatic failover (Automatic failover): When a primary server fails, Sentinel starts an automated failover operation that upgrades one of the failed primary servers from the server to the new primary server. And let the other from the failed master server replicate to the new master server, and when the client attempts to connect to the failed primary server, the cluster also returns the address of the new home server to the client, allowing the cluster to use the new primary server instead of the failed server.

First, we introduce the Redis Sentinel service-side configuration

This is the Redis master server with a port number of 6479

# #redis. conf
# #redis-0, default to Def_master
Port 6479
# #授权密码, please keep each configuration consistent
Requirepass 123456
Masterauth 123456
# #暂且禁用指令重命名
# #rename-command
# #开启AOF, disable snapshot
AppendOnly Yes
Save 900 1
Save 300 10
Save 60 10000
# #slaveof No one
Slave-read-only Yes




This is the port number 6480 from the server

# #redis. conf
# #redis-0, default to Def_master
Port 6480
slaveof 127.0.0.1 6479
# #授权密码, please keep each configuration consistent
Requirepass 123456
Masterauth 123456
# #暂且禁用指令重命名
# #rename-command
# #开启AOF, disable snapshot
AppendOnly Yes
Save 900 1
Save 300 10
Save 60 10000
# #slaveof No one
Slave-read-only Yes



This is the Sentinel Cluster Manager sentinel.conf configuration

# #redis-0
# #sentinel实例之间的通讯端口
Port 26379
# #指定sentinel使用的端口, cannot conflict with Redis-server running instance's port, 1 means that at least one of the primary servers found from the server will automatically master-slave switching
Sentinel Monitor Def_master 127.0.0.1 6479 1
# #连接redis服务密码
Sentinel Auth-pass Def_master 123456
# #表示如果5s内mymaster没响应, it is considered that the primary server has failed
Sentinel Down-after-milliseconds Def_master 50000
# #表示如果master重新选出来后, how many other slave nodes can synchronize cache from the new master at the same time, obviously the larger the value, the faster the overall speed of all slave nodes completes the sync switch, but if someone is accessing these slave right now, May cause the read to fail, the influence face will be more extensive. The most Baoding setting is 1, at the same time, only one can do this, so other slave can continue to service, but all slave complete the cache update synchronization process will slow down.
Sentinel Parallel-syncs Def_master 1
Indicates that if the mysater is still not alive after 90 seconds, start the failover (failover) and choose one of the remaining slave to upgrade to master.
Sentinel Failover-timeout Def_master 900000


When the configuration is written, start the Reids service, which I tested in the Windows environment, and the commands are different under Linux.


Enter the cmd command to enter the console,

Open the Redis file location and enter Redis-server.exe redis6479.conf to start the Reids primary server.

Then open from the server location, enter Redis-server.exe redis6480.conf boot reids from the server.

Then start Sentinel, open the file location and enter Redis-server sentinel.conf--sentinel boot manager.

When it's over, the service opens successfully.


Here is the client connection service-side code writing:

Spring provides a subproject of spring data Redis, and I'm using spring data Redis

Spring's configuration file:

Spring-data-redis.xml


<?xml version= "1.0" encoding= "UTF-8"?>
<beans
Xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "Http://www.springframework.org/schema/context"
xmlns:p= "http://www.springframework.org/schema/p"
Xmlns:c= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/C"
Xmlns:cache= "Http://www.springframework.org/schema/cache"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:tx= "Http://www.springframework.org/schema/tx"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.2.xsd
Http://www.springframework.org/schema/aop
Http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
Http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd ">

<context:component-scan base-package= "Org.tht.service"/>

<cache:annotation-driven></cache:annotation-driven>

<bean id= "Redissentinelconfiguration"

class= "Org.springframework.data.redis.connection.RedisSentinelConfiguration" >
<!--here Def_master is the name of the cluster manager, we only need to connect Sentinel,sentinel at the client will help us to manage Redis server-->
<property name= "Def_master" >

<bean class= "Org.springframework.data.redis.connection.RedisNode" >

<property name= "name" value= "MyMaster" ></property>

</bean>

</property>

<property name= "Sentinels" >

<set>
<bean class= "Org.springframework.data.redis.connection.RedisNode" >


<constructor-arg name= "host" value= "127.0.0.1"/>


<constructor-arg name= "Port" value= "26379"/>

</bean>

</set>

</property>

</bean>


<bean id= "Jeidsconnectionfactory"


class= "Org.springframework.data.redis.connection.jedis.JedisConnectionFactory" >
<property name= "Password" value= "123456" ></property>
<constructor-arg ref= "Redissentinelconfiguration"/>

</bean>





<bean id= "Redistemplate" class= "Org.springframework.data.redis.core.RedisTemplate"


p:connection-factory-ref= "Jeidsconnectionfactory"/>

<bean
Id= "CacheManager"
Class= "Org.springframework.data.redis.cache.RedisCacheManager"
c:template-ref= "Redistemplate"/>

</beans>

Now we write the method:


@Cacheable (value= "Messagecache", key= "#name")
public string GetMessage (string name) {

return Userservice.findbyname (name);
}

This is the query method, @Cacheable (value= "Messagecache", key= "#name")

This annotation is the query Redis cache, Value: namespace, key: Returns the corresponding key for the data. If the key is not in the cache, it queries the database and stores the returned value in Redis and reads the data directly from the cache.



Update cache

@CachePut (value= "Messagecache", key= "#name")
public string Updatemessage (string name) {

return Userservice.findbyname (name);
}

This annotation is to modify the Redis cache @cacheput (value= "Messagecache", key= "#name")



Empty the namespace for all caches under Messagecache
@CacheEvict (value= "Messagecache", Allentries=true)
public void Deleteoperationauthbypageurlcache () {


}


Empty a cache with the namespace Messagecache key to name
@CacheEvict (value= "Messagecache", allentries=true,key= "#name")
public void Deleteoperationauthbypageurlcache () {


}


The above code after I tested, no problem, when the primary server will automatically upgrade from the server to the main server, the two Redis server data will be synchronized, this cluster mode without worrying about the loss of data after the server hanging off.


Before the school Redis I also learned memcached, said to choose Redis below will explain the reason.


The following is memcached distributed code based on client:

Google offers memcached and spring-integrated components simple spring memcached, which is spring-memcache.xml configuration


<?xml version= "1.0" encoding= "UTF-8"?>
<beans
Xmlns= "Http://www.springframework.org/schema/beans"
Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"
xmlns:context= "Http://www.springframework.org/schema/context"
xmlns:aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"
xmlns:tx= "Http://www.springframework.org/schema/tx"
Xsi:schemalocation= "Http://www.springframework.org/schema/beans
Http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
Http://www.springframework.org/schema/context
Http://www.springframework.org/schema/context/spring-context-3.2.xsd
Http://www.springframework.org/schema/aop
Http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
">

<context:component-scan base-package= "Org.tht.service"/>

<aop:aspectj-autoproxy></aop:aspectj-autoproxy>

<import resource= "Simplesm-context.xml"/>
<!--default a client-->
<bean name= "defaultmemcachedclient" class= "Com.google.code.ssm.CacheFactory" >
<property name= "Cacheclientfactory" >
<bean name= "Cacheclientfactory" class= "Com.google.code.ssm.providers.xmemcached.MemcacheClientFactoryImpl"/ >
</property>
<property name= "Addressprovider" >
<bean class= "Com.google.code.ssm.config.DefaultAddressProvider" >

<!--server address, where distributed--> are implemented
<property name= "Address" value= "127.0.0.1:11211,192.168.1.227:12677"/>
</bean>
</property>
<!--consistency Hash ~. ~-->
<property name= "Configuration" >
<bean class= "Com.google.code.ssm.providers.CacheConfiguration" >
<property name= "consistenthashing" value= "true"/>
</bean>
</property>
</bean>
<bean class= "Com.google.code.ssm.Settings" >
<property name= "order" value= "/>"
</bean>
</beans>


Here's how:

/**
* When executing the Getuserbyid query method, the system first obtains the ID corresponding entity from the cache
* If the entity is not yet cached, execute the query method and put the query results in the cache
*/
@ReadThroughSingleCache (Namespace = "Test")
Public Cachebean Getuserbyid (@ParameterValueKeyProvider String userId) throws exception{
System.out.println ("No Cache Hits");
Cachebean cachebean=new Cachebean ();
Cachebean.setuserid (USERID);
Cachebean.setusername ("Zhao Liu");
return Cachebean;
}


/**
* When the Delete method is executed, the system deletes the entity that corresponds to the ID in the cache
*/
@InvalidateSingleCache (namespace= "test")
public void Delete (@ParameterValueKeyProvider Integer userId) {
System.out.println (USERID);
}


/**
* When the Update method is executed, the system updates the entity in the cache that corresponds to the ID
* Update entity content to the entity described by the @*dataupdatecontent tag
*/
@UpdateSingleCache (namespace= "test")
public void Update (@ParameterValueKeyProvider @ParameterDataUpdateContent Cachebean Cachebean) {
System.out.println (Cachebean.getusername ());
}


Now let's talk about the difference between Redis and memcached:

Before that you may have looked at a lot of differences on the Internet, and here I'm just saying that I'm using these two caching experiences.

The difference between 1:memcached is based on the client side (described below), while the Redis distribution is based on the server (which is clearly written above)

Difference 2:redis You can delete all keys under the namespace based on the namespace, and memcached must specify key (you want to delete all keys under the namespace, you can only detect all keys under that namespace before you delete them)

Difference 3:redis support data persistence, you can keep the data in memory on disk, restart can be loaded again to use, and memcached server reboot after all cached data will be emptied.

The above 3 differences are my firsthand experience, there are many differences here not one by one, can be found on the Internet.


I rookie one, big God don't spray, above just I learn a little experience, also just understand a point of fur, also have a lot of don't know place, hope can communicate with you, common progress.

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.