1. 程式人生 > >劍指架構師系列-Redis安裝與使用

劍指架構師系列-Redis安裝與使用

div caching callback 集成 lease work classpath .com cut

1、安裝Redis

我們在VMware中安裝CentOS 64位系統後,在用戶目錄下下載安裝Redis。

下載redis目前最穩定版本也是功能最完善,集群支持最好並加入了sentinel(哨兵-高可用)功能的redis-stable版, http://download.redis.io/releases/
wget http://download.redis.io/releases/redis-stable.tar.gz
tar -xzvf redis-stable.tar.gz
cd redis-stable
make PREFIX=/usr/local/redis01 install  
cd /usr/local/redis01/bin
 

加上`&`號使redis以後臺程序方式運行

./redis-server &

或者也可以到 redis-stable/src目錄下進行啟動。

檢測後臺進程是否存在

ps -ef |grep redis

檢測6379端口是否在監聽

netstat -lntp | grep 6379

或者我們可以直接到redis-stable目錄下修改配置文redis.conf,找到如下配置:

daemonize yes

# When running daemonized, Redis writes a pid file in /var/run/redis.pid by
# default. You can specify a custom pid file location here.
pidfile "/var/run/redis/redis01.pid"

# Accept connections on the specified port, default is 6379.
# If port 0 is specified Redis will not listen on a TCP socket.
port 7001

將daemonize值改為yes,修改進行pid的存在路徑,然後重新指定一下port端口。

最後我們設置一下redis的log日誌存放的地方,如果沒有redis目錄,需要切換到路徑下進行新建。

logfile "/var/log/redis/redis01.log"

修改配置文件後我們需要指定使用哪個配置文件啟動Redis

./redis-server ../redis.conf

用`redis-cli`客戶端檢測連接是否正常

./redis-cli
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> set key "hello world"
OK

我們可以在Windows下直接下載一個RedisClient直接連接VMware中安裝的Redis即可。如下圖。

技術分享

如果連接不上,需要關閉一下防火墻,使用

iptables -F

來禁用linux的防火墻或者使用:

vi /etc/selinux/config

然後把修改 SELINUX=enforcing的值為disabled

Spring Boot集成Redis

在mazhi工程下新建Maven Module,名稱為mazhi-redis,然後在 pom.xml文件中添加redis的包引用和spring boot的包引用,如下:

 <!-- Add typical dependencies for a web application -->
    <dependencies>
       <dependency>
			<groupId>org.mazhi</groupId>
			<artifactId>mazhi-core</artifactId>
			<version>0.0.1-SNAPSHOT</version>
	   </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
         <!-- redius  -->
	    <dependency>
			<groupId>org.springframework.session</groupId>
			<artifactId>spring-session-data-redis</artifactId>
			<version>1.0.0.RELEASE</version>
		</dependency>
    </dependencies>

然後引入application.yml文件,指定端口為8081。並且在src/java/main的org.mazhi.redis目錄下新建Application.java文件,內容如下:

@SpringBootApplication
public class Application {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

}

下面就來為系統配置Redis了,在org.mazhi.redis.config目錄下新建RedisCacheConfig.java文件,內容如下:

@Configuration
@PropertySource(value = "classpath:/redis.properties")
@EnableCaching
public class RedisCacheConfig extends CachingConfigurerSupport {
	
		  @Value("${spring.redis.host}")
		  private String host;
		  @Value("${spring.redis.port}")
		  private int port;
		  @Value("${spring.redis.timeout}")
		  private int timeout;
		  
		  @Bean
		  public KeyGenerator wiselyKeyGenerator(){
		      return new KeyGenerator() {
		          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();
		          }
		      };
		  }
		  @Bean
		  public JedisConnectionFactory redisConnectionFactory() {
		      JedisConnectionFactory factory = new JedisConnectionFactory();
		      factory.setHostName(host);
		      factory.setPort(port);
		      factory.setTimeout(timeout); //設置連接超時時間
		      return factory;
		  }
		  @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;
		  }
		  @Bean
		  public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
		      StringRedisTemplate template = new StringRedisTemplate(factory);
		      setSerializer(template); //設置序列化工具,這樣ReportBean不需要實現Serializable接口
		      template.afterPropertiesSet();
		      return template;
		  }
		  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);
		  }
}

然後新建redis.properties配置文件,內容如下:

spring.redis.database=0
spring.redis.host=192.168.2.129
# Login password of the redis server.
spring.redis.password= 
spring.redis.pool.max-active=8
spring.redis.pool.max-idle=8
spring.redis.pool.max-wait=-1
spring.redis.pool.min-idle=0
spring.redis.port=7001
# Name of Redis server.
spring.redis.sentinel.master= 
# Comma-separated list of host:port pairs.
spring.redis.sentinel.nodes=  
spring.redis.timeout=0

註意指定spring.redis.host和spring.redis.port為你的redis配置。

在org.mazhi.redis.web目錄下新建RedisTestCtrl.java,對Redis進行簡單的CRUD操作,如下:

@RestController
@RequestMapping(value = "/redis")
public class RedisTestCtrl {
	@Autowired
	private StringRedisTemplate redisTemplate;

	@RequestMapping(value = "/addKey")
	public void addKey() {
		redisTemplate.execute(new RedisCallback<Object>() {  
            public Object doInRedis(RedisConnection connection) throws DataAccessException {  
                connection.set(  // 插入鍵為test,值為hello的鍵值對
                        redisTemplate.getStringSerializer().serialize("test"), 
                        redisTemplate.getStringSerializer().serialize("hello")
                );  
                return null;  
            }  
       });  
		
	}
	
	@RequestMapping(value = "/deleteKey")
	public void deleteKey() {
		redisTemplate.delete("test");  // 刪除數據庫中鍵為test的鍵值對
		
	}
}

這樣在瀏覽器中訪問一下:

http://localhost:8081/redis/addKey   

執行添加的url後,可以在RedisClient中查看,如下:

技術分享

然後執行:

http://localhost:8081/redis/delete  

查看RedisClient,鍵值被刪除。

劍指架構師系列-Redis安裝與使用